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.
- package/.env.example +0 -1
- package/.release-target +1 -1
- package/README.md +25 -1
- package/bin/toolnet-memory +5 -0
- package/bundle/agy-hook.js +67 -67
- package/bundle/agy.js +61 -61
- package/bundle/api.js +15 -15
- package/bundle/auto-integrate.js +28 -28
- package/bundle/background-refresh.js +7 -7
- package/bundle/claude-hook.js +51 -50
- package/bundle/codex-context.js +25 -24
- package/bundle/codex.js +71 -71
- package/bundle/context-runtime.js +45 -44
- package/bundle/context.js +15 -15
- package/bundle/continuity-certify.js +13 -13
- package/bundle/copilot-hook.js +87 -85
- package/bundle/copilot.js +4 -4
- package/bundle/cursor-hook.js +87 -85
- package/bundle/cursor.js +4 -4
- package/bundle/doctor.js +4 -4
- package/bundle/full-index.js +20 -20
- package/bundle/gc.js +3 -0
- package/bundle/graph-index.js +4 -4
- package/bundle/graph-ui.js +3 -3
- package/bundle/grok-hook.js +60 -59
- package/bundle/grok.js +5 -5
- package/bundle/handoff-refresh.js +10 -10
- package/bundle/help-cli.js +4 -4
- package/bundle/impact.js +4 -4
- package/bundle/incremental.js +5 -4
- package/bundle/init.js +37 -37
- package/bundle/integration-status.js +4 -4
- package/bundle/kiro-hook.js +82 -81
- package/bundle/learner.js +6 -6
- package/bundle/mcp.js +17 -17
- package/bundle/memory-agent.js +7 -7
- package/bundle/memory-query.js +7 -7
- package/bundle/opencode.js +80 -80
- package/bundle/project-manual.js +7 -7
- package/bundle/recovery-certify.js +15 -15
- package/bundle/runtime.js +13 -12
- package/bundle/semantic.js +5 -5
- package/bundle/snapshot.js +4 -4
- package/bundle/status-cli.js +4 -4
- package/bundle/toolnet-cli.js +60 -60
- package/bundle/work-continuity.js +7 -7
- package/package.json +9 -3
- package/release-manifest.json +54 -3
package/bundle/codex.js
CHANGED
|
@@ -1,61 +1,61 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function
|
|
3
|
-
`,{encoding:"utf8",mode:384}),xo(s,r)}function hn(t,e){return{id:t.id,name:t.name,remote:t.remote,rootPath:e,createdAt:t.createdAt,updatedAt:t.updatedAt,graphVersion:t.graphVersion,memoryVersion:t.memoryVersion,metadata:t.metadata}}var ne=class{detect(e=process.cwd()){let n=me(e),r=Eo(n),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(p=>Pt($e(r,p))),i=Po(n,o?r:void 0);if(i){let p=Et(i),l=Oo(p);return l.rootPath!==i&&(l.rootPath=i,l.updatedAt=new Date().toISOString(),yn(i,l)),hn(l,i)}let a=new Date().toISOString(),c=Co(r),u={version:1,id:Ao(r),name:c,remote:c,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return yn(r,u),hn(u,r)}};var To=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_\-]{20,}\b/g},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._\-]{16,}\b/gi},{type:"jwt",regex:/\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\b/g},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g},{type:"password_assignment",regex:/\b(password|passwd|pwd)\s*[:=]\s*["']?[^"'\s]{6,}["']?/gi},{type:"secret_assignment",regex:/\b(secret|api[_-]?key|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?[^"'\s]{8,}["']?/gi},{type:"cookie",regex:/\b(cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi}],Ke=class{scan(e){let n=[];for(let r of To){let s=new RegExp(r.regex.source,r.regex.flags);for(let o of e.matchAll(s))n.push({type:r.type,value:o[0]})}return n}hasSecrets(e){return this.scan(e).length>0}};var G=class{scanner=new Ke;sanitize(e){let n=e,r=this.scanner.scan(e),s=new Set;for(let o of r)s.add(o.type),n=n.split(o.value).join(`[REDACTED:${o.type}]`);return{text:n,redacted:r.length,secretTypes:[...s]}}sanitizeValue(e){if(typeof e=="string")return this.sanitize(e).text;if(Array.isArray(e))return e.map(n=>this.sanitizeValue(n));if(e&&typeof e=="object"){let n={};for(let[r,s]of Object.entries(e)){let o=r.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");o.includes("password")||o.includes("passwd")||o==="pwd"||o.includes("secret")||o.includes("token")||o.includes("cookie")||o.includes("authorization")||o.includes("apikey")||o.includes("accesskey")||o.includes("privatekey")||o.includes("clientsecret")||o.includes("credential")?n[r]="[REDACTED]":n[r]=this.sanitizeValue(s)}return n}return e}};import{homedir as ti}from"node:os";import{join as ni}from"node:path";import{DeleteObjectCommand as Ro,GetObjectCommand as No,HeadObjectCommand as _o,ListObjectsV2Command as $o,PutObjectCommand as Ko,S3Client as Fo}from"@aws-sdk/client-s3";import{getSignedUrl as Wo}from"@aws-sdk/s3-request-presigner";var Fe=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Fo({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Ko({Bucket:this.bucket,Key:e,Body:s,ContentType:r}))}async get(e){let n=await Wo(this.client,new No({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await this.client.send(new _o({Bucket:this.bucket,Key:e})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(e){await this.client.send(new Ro({Bucket:this.bucket,Key:e}))}async list(e=""){let n=[],r;do{let s=await this.client.send(new $o({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let o of s.Contents??[])o.Key&&n.push({key:o.Key,size:o.Size,updatedAt:o.LastModified?.toISOString()});r=s.IsTruncated?s.NextContinuationToken:void 0}while(r);return n}};import{access as vn,mkdir as Lo,readFile as Do,readdir as zo,rm as qo,stat as wn,writeFile as Bo}from"node:fs/promises";import{dirname as Jo,join as Ho,relative as bn,resolve as Vo}from"node:path";var ge=class{constructor(e){this.root=e}root;name="local";path(e){let n=e.replace(/^\/+/,"");return Vo(this.root,n)}async put(e,n){let r=this.path(e);await Lo(Jo(r),{recursive:!0}),await Bo(r,n)}async get(e){try{return await Do(this.path(e))}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT")return null;throw n}}async getText(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await vn(this.path(e)),!0}catch{return!1}}async delete(e){await qo(this.path(e),{force:!0})}async list(e=""){let n=this.path(e),r=[];try{await vn(n)}catch{return r}let s=async i=>{let a=await zo(i,{withFileTypes:!0});for(let c of a){let u=Ho(i,c.name);if(c.isDirectory()){await s(u);continue}let p=await wn(u);r.push({key:bn(this.root,u),size:p.size,updatedAt:p.mtime.toISOString()})}},o=await wn(n);return o.isDirectory()?await s(n):r.push({key:bn(this.root,n),size:o.size,updatedAt:o.mtime.toISOString()}),r}};import{DeleteObjectCommand as Go,GetObjectCommand as Uo,HeadObjectCommand as Yo,ListObjectsV2Command as Xo,PutObjectCommand as Qo,S3Client as Zo}from"@aws-sdk/client-s3";import{getSignedUrl as ei}from"@aws-sdk/s3-request-presigner";var ye=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new Zo({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Qo({Bucket:this.bucket,Key:e,Body:s,ContentType:r}))}async get(e){let n=await ei(this.client,new Uo({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await this.client.send(new Yo({Bucket:this.bucket,Key:e})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(e){await this.client.send(new Go({Bucket:this.bucket,Key:e}))}async list(e=""){let n=[],r;do{let s=await this.client.send(new Xo({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let o of s.Contents??[])o.Key&&n.push({key:o.Key,size:o.Size,updatedAt:o.LastModified?.toISOString()});r=s.IsTruncated?s.NextContinuationToken:void 0}while(r);return n}};function Ot(t,e){return console.warn(e),new ge(t)}function xn(t){let e=t.localRoot??ni(ti(),".toolnet-memory","storage");if(t.provider==="r2"){let n=t.r2;return n?.accountId&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new ye({name:"r2",endpoint:`https://${n.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:n.bucket,forcePathStyle:!0,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Ot(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(t.provider==="s3"){let n=t.s3;return n?.bucket&&n.accessKeyId&&n.secretAccessKey?new ye({name:"s3",endpoint:n.endpoint,region:n.region??"us-east-1",bucket:n.bucket,forcePathStyle:n.forcePathStyle??!1,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Ot(e,"[storage] S3 credentials missing. Using local fallback.")}if(t.provider==="huggingface"){let n=t.huggingface;return n?.namespace&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new Fe({namespace:n.namespace,bucket:n.bucket,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Ot(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new ge(e)}function ri(t){return new Promise(e=>setTimeout(e,t))}async function jn(t,e={}){let n=Math.max(1,e.attempts??3),r=e.baseDelayMs??150,s=e.maxDelayMs??2e3,o;for(let i=1;i<=n;i++)try{return await t()}catch(a){if(o=a,i>=n)break;let c=Math.min(s,r*2**(i-1)),u=Math.floor(Math.random()*Math.max(1,c*.2));await ri(c+u)}throw o}var si=new Set(["put","get","getText","delete","list"]);function Cn(t,e={}){return new Proxy(t,{get(n,r){let s=Reflect.get(n,r,n);return typeof s!="function"?s:si.has(r)?(...o)=>jn(()=>Promise.resolve(s.apply(n,o)),e):s.bind(n)}})}function In(t){let e=t.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function An(t){let e=t.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let n=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let s=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return s?`${s[1]}memory/records/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),s?`${s[1]}memory/vectors/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),s?`${s[1]}code/graph/${s[2]}`:e))}var We=class{constructor(e,n,r,s){this.provider=e;this.name=e.name,this.projectId=n,this.projectName=r,this.folder=In(s??r),this.sourcePrefix=`projects/${n}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,n=new Date().toISOString(),r=n,s=await this.provider.getText(e);if(s){let i;try{i=JSON.parse(s)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${a instanceof Error?a.message:String(a)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(r=i.createdAt)}let o={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:n};await this.provider.put(e,JSON.stringify(o,null,2)+`
|
|
4
|
-
`,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=
|
|
5
|
-
`,{encoding:"utf8",mode:384}),
|
|
1
|
+
import{existsSync as zd,readFileSync as qd}from"node:fs";import{spawn as Vd}from"node:child_process";import{homedir as Hd}from"node:os";import{join as Bd}from"node:path";import{existsSync as vo,readFileSync as wo}from"node:fs";import{homedir as bo}from"node:os";import{join as xo}from"node:path";function jo(t){let e=t.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Co(){let t=process.env.TOOLNET_GLOBAL_ENV??xo(bo(),".config","toolnet-memory",".env");if(!vo(t))return;let e=wo(t,"utf8");for(let n of e.split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#"))continue;r.startsWith("export ")&&(r=r.slice(7));let s=r.indexOf("=");if(s<=0)continue;let o=r.slice(0,s).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)&&process.env[o]===void 0&&(process.env[o]=jo(r.slice(s+1)))}}Co();function fe(t,e){return t===void 0?e:["1","true","yes","on"].includes(t.toLowerCase())}function me(t,e){if(!t)return e;let n=Number(t);return Number.isFinite(n)?n:e}function Ke(){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: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: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:me(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as Io}from"node:crypto";import{existsSync as Fe,mkdirSync as Ao,readFileSync as Mo,renameSync as Po,writeFileSync as Eo}from"node:fs";import{basename as Oo,dirname as Le,join as ge,parse as bn,resolve as re}from"node:path";var xn=".toolnet",To="project.json";function Ro(t){return Io("sha256").update(t).digest("hex").slice(0,16)}function We(t){return ge(t,xn,To)}function No(t){return Fe(We(t))}function Sn(t,e){let n=re(t),r=bn(n).root;for(;;){if(No(n))return n;if(n===r||e&&n===re(e))break;let s=Le(n);if(s===n)break;n=s}return null}function kn(t){let e=re(t),n=bn(e).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(o=>Fe(ge(e,o))))return e;if(e===n)break;let s=Le(e);if(s===e)break;e=s}return re(t)}function vn(t){let e;try{e=JSON.parse(Mo(t,"utf8"))}catch(s){throw new Error(`Invalid ToolNet project manifest: ${t}: ${s instanceof Error?s.message:String(s)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${t}`);let n=e;if(typeof n.id!="string"||!n.id.trim())throw new Error(`ToolNet project manifest is missing id: ${t}`);if(typeof n.name!="string"||!n.name.trim())throw new Error(`ToolNet project manifest is missing name: ${t}`);let r=new Date().toISOString();return{version:1,id:n.id,name:n.name,remote:typeof n.remote=="string"&&n.remote.trim()?n.remote:n.name,rootPath:typeof n.rootPath=="string"?n.rootPath:Le(Le(t)),createdAt:typeof n.createdAt=="string"?n.createdAt:r,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:r,graphVersion:typeof n.graphVersion=="number"?n.graphVersion:0,memoryVersion:typeof n.memoryVersion=="number"?n.memoryVersion:0,metadata:n.metadata&&typeof n.metadata=="object"?n.metadata:void 0}}function wn(t,e){let n=ge(t,xn);Ao(n,{recursive:!0});let r=We(t),s=`${r}.tmp-${process.pid}`;Eo(s,JSON.stringify(e,null,2)+`
|
|
3
|
+
`,{encoding:"utf8",mode:384}),Po(s,r)}function Rt(t,e){return{id:t.id,name:t.name,remote:t.remote,rootPath:e,createdAt:t.createdAt,updatedAt:t.updatedAt,graphVersion:t.graphVersion,memoryVersion:t.memoryVersion,metadata:t.metadata}}var se=class{findExisting(e=process.cwd()){let n=re(e),r=kn(n),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(c=>Fe(ge(r,c))),i=Sn(n,o?r:void 0);if(!i)return null;let a=vn(We(i));return Rt(a,i)}requireExisting(e=process.cwd()){let n=this.findExisting(e);if(!n)throw new Error("PROJECT_NOT_INITIALIZED");return n}detect(e=process.cwd()){let n=re(e),r=kn(n),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(p=>Fe(ge(r,p))),i=Sn(n,o?r:void 0);if(i){let p=We(i),l=vn(p);return l.rootPath!==i&&(l.rootPath=i,l.updatedAt=new Date().toISOString(),wn(i,l)),Rt(l,i)}let a=new Date().toISOString(),c=Oo(r),u={version:1,id:Ro(r),name:c,remote:c,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return wn(r,u),Rt(u,r)}};var _o=[{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"}],$o=new Set(["example","example-key","example-token","changeme","change-me","password","secret","your-api-key","your-token","<token>","<secret>","<password>","[redacted]"]);function jn(t){return t.normalize("NFKC").trim().toLowerCase()}function Ko(t){if(t.length===0)return 0;let e=new Map;for(let r of t)e.set(r,(e.get(r)??0)+1);let n=0;for(let r of e.values()){let s=r/t.length;n-=s*Math.log2(s)}return n}function Fo(t){return/^[a-f0-9]{32}$/iu.test(t)||/^[a-f0-9]{40}$/iu.test(t)||/^[a-f0-9]{64}$/iu.test(t)}function Lo(t,e,n){let r=t.slice(Math.max(0,e-48),e),s=t.slice(n,Math.min(t.length,n+16));return/\b(?:token|secret|key|credential|authorization|password|passwd|apikey|api_key|access[_-]?key)\b/iu.test(`${r} ${s}`)}function Wo(t,e){return t.start<e.end&&e.start<t.end}function Cn(t){return t.sort((e,n)=>e.start!==n.start?e.start-n.start:n.end-n.start-(e.end-e.start))}var De=class{allowValues=new Set;enableEntropyHeuristic;constructor(e={}){for(let n of e.allowValues??[]){let r=jn(n);r&&this.allowValues.add(r)}this.enableEntropyHeuristic=e.enableEntropyHeuristic??!0}scan(e){let n=[];for(let o of _o){let i=new RegExp(o.regex.source,o.regex.flags);for(let a of e.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(e));let r=Cn(n),s=[];for(let o of r)s.some(i=>Wo(i,o))||s.push(o);return Cn(s)}hasSecrets(e){return this.scan(e).length>0}allowed(e){let n=jn(e);return $o.has(n)?!0:this.allowValues.has(n)}entropyMatches(e){let n=[],r=/[A-Za-z0-9_+/=-]{32,160}/g;for(let s of e.matchAll(r)){if(s.index===void 0||!s[0])continue;let o=s[0];this.allowed(o)||Fo(o)||!/[A-Za-z]/u.test(o)||!/[0-9]/u.test(o)||Lo(e,s.index,s.index+o.length)&&(Ko(o)<3.7||n.push({type:"high_entropy_secret",value:o,start:s.index,end:s.index+o.length,confidence:"heuristic"}))}return n}};var H=class{scanner;constructor(e={}){this.scanner=new De(e)}sanitize(e){let n=this.scanner.scan(e);if(n.length===0)return{text:e,redacted:0,secretTypes:[]};let r=e,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(e){if(typeof e=="string")return this.sanitize(e).text;if(Array.isArray(e))return e.map(n=>this.sanitizeValue(n));if(e&&typeof e=="object"){let n={};for(let[r,s]of Object.entries(e)){let o=r.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");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 e}};var Do=new H;function ye(t){return Do.sanitizeValue(t)}import{homedir as li}from"node:os";import{join as di}from"node:path";import{DeleteObjectCommand as zo,GetObjectCommand as qo,HeadObjectCommand as Vo,ListObjectsV2Command as Ho,PutObjectCommand as Bo,S3Client as Jo}from"@aws-sdk/client-s3";import{getSignedUrl as Go}from"@aws-sdk/s3-request-presigner";var ze=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Jo({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Bo({Bucket:this.bucket,Key:e,Body:s,ContentType:r}))}async get(e){let n=await Go(this.client,new qo({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await this.client.send(new Vo({Bucket:this.bucket,Key:e})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(e){await this.client.send(new zo({Bucket:this.bucket,Key:e}))}async list(e=""){let n=[],r;do{let s=await this.client.send(new Ho({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let o of s.Contents??[])o.Key&&n.push({key:o.Key,size:o.Size,updatedAt:o.LastModified?.toISOString()});r=s.IsTruncated?s.NextContinuationToken:void 0}while(r);return n}};import{access as In,mkdir as Uo,readFile as Yo,readdir as Xo,rm as Qo,stat as An,writeFile as Zo}from"node:fs/promises";import{dirname as ei,join as ti,relative as Mn,resolve as ni}from"node:path";var he=class{constructor(e){this.root=e}root;name="local";path(e){let n=e.replace(/^\/+/,"");return ni(this.root,n)}async put(e,n){let r=this.path(e);await Uo(ei(r),{recursive:!0}),await Zo(r,n)}async get(e){try{return await Yo(this.path(e))}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT")return null;throw n}}async getText(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await In(this.path(e)),!0}catch{return!1}}async delete(e){await Qo(this.path(e),{force:!0})}async list(e=""){let n=this.path(e),r=[];try{await In(n)}catch{return r}let s=async i=>{let a=await Xo(i,{withFileTypes:!0});for(let c of a){let u=ti(i,c.name);if(c.isDirectory()){await s(u);continue}let p=await An(u);r.push({key:Mn(this.root,u),size:p.size,updatedAt:p.mtime.toISOString()})}},o=await An(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 ri,GetObjectCommand as si,HeadObjectCommand as oi,ListObjectsV2Command as ii,PutObjectCommand as ai,S3Client as ci}from"@aws-sdk/client-s3";import{getSignedUrl as ui}from"@aws-sdk/s3-request-presigner";var Se=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new ci({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new ai({Bucket:this.bucket,Key:e,Body:s,ContentType:r}))}async get(e){let n=await ui(this.client,new si({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await this.client.send(new oi({Bucket:this.bucket,Key:e})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(e){await this.client.send(new ri({Bucket:this.bucket,Key:e}))}async list(e=""){let n=[],r;do{let s=await this.client.send(new ii({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let o of s.Contents??[])o.Key&&n.push({key:o.Key,size:o.Size,updatedAt:o.LastModified?.toISOString()});r=s.IsTruncated?s.NextContinuationToken:void 0}while(r);return n}};function Nt(t,e){return console.warn(e),new he(t)}function Pn(t){let e=t.localRoot??di(li(),".toolnet-memory","storage");if(t.provider==="r2"){let n=t.r2;return n?.accountId&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new Se({name:"r2",endpoint:`https://${n.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:n.bucket,forcePathStyle:!0,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Nt(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(t.provider==="s3"){let n=t.s3;return n?.bucket&&n.accessKeyId&&n.secretAccessKey?new Se({name:"s3",endpoint:n.endpoint,region:n.region??"us-east-1",bucket:n.bucket,forcePathStyle:n.forcePathStyle??!1,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Nt(e,"[storage] S3 credentials missing. Using local fallback.")}if(t.provider==="huggingface"){let n=t.huggingface;return n?.namespace&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new ze({namespace:n.namespace,bucket:n.bucket,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Nt(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new he(e)}function pi(t){return new Promise(e=>setTimeout(e,t))}async function En(t,e={}){let n=Math.max(1,e.attempts??3),r=e.baseDelayMs??150,s=e.maxDelayMs??2e3,o;for(let i=1;i<=n;i++)try{return await t()}catch(a){if(o=a,i>=n)break;let c=Math.min(s,r*2**(i-1)),u=Math.floor(Math.random()*Math.max(1,c*.2));await pi(c+u)}throw o}var fi=new Set(["put","get","getText","delete","list"]);function On(t,e={}){return new Proxy(t,{get(n,r){let s=Reflect.get(n,r,n);return typeof s!="function"?s:fi.has(r)?(...o)=>En(()=>Promise.resolve(s.apply(n,o)),e):s.bind(n)}})}function Tn(t){let e=t.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function Rn(t){let e=t.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let n=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let s=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return s?`${s[1]}memory/records/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),s?`${s[1]}memory/vectors/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),s?`${s[1]}code/graph/${s[2]}`:e))}var qe=class{constructor(e,n,r,s){this.provider=e;this.name=e.name,this.projectId=n,this.projectName=r,this.folder=Tn(s??r),this.sourcePrefix=`projects/${n}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,n=new Date().toISOString(),r=n,s=await this.provider.getText(e);if(s){let i;try{i=JSON.parse(s)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${a instanceof Error?a.message:String(a)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(r=i.createdAt)}let o={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:n};await this.provider.put(e,JSON.stringify(o,null,2)+`
|
|
4
|
+
`,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=Rn(e),e===this.sourcePrefix)return this.targetPrefix;if(e.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+e.slice(this.sourcePrefix.length);if(e===this.targetPrefix||e.startsWith(`${this.targetPrefix}/`))return e;if(e.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${e}`].join(" "));return e}async put(e,n,r){return await this.ensureRegistered(),this.provider.put(this.key(e),n,r)}async get(e){return await this.ensureRegistered(),this.provider.get(this.key(e))}async getText(e){return await this.ensureRegistered(),this.provider.getText(this.key(e))}async delete(e){return await this.ensureRegistered(),this.provider.delete(this.key(e))}async exists(e){return await this.ensureRegistered(),this.provider.exists(this.key(e))}async list(e){return await this.ensureRegistered(),this.provider.list(this.key(e))}};import{join as vi}from"node:path";import{createHash as mi}from"node:crypto";import{dirname as gi}from"node:path";import{mkdirSync as yi,readFileSync as hi,renameSync as Si,writeFileSync as ki}from"node:fs";function w(t){return mi("sha256").update(t).digest("hex")}function _t(t){if(Array.isArray(t))return t.map(_t);if(t&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=_t(e[r]);return n}return t}function Nn(t){return JSON.stringify(_t(t))}function _n(t){try{return JSON.parse(hi(t,"utf8"))}catch{return null}}function R(t,e){yi(gi(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;ki(n,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,{encoding:"utf8",mode:384}),Si(n,t)}function $n(t,e){let n=t.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`${e}--${s}`;let o=r.slice(0,100);return o===n&&n.length<=100?o:`${o.slice(0,85)}--${s}`}function Ve(t,e,n){let r=e.trim(),s=n.trim();if(!r)throw new Error("Session agent is required");if(!s)throw new Error("Native session ID is required");let o=$n(r.toLowerCase(),"agent"),i=$n(s,"session");return{projectId:t.id,projectName:t.name,projectRoot:t.rootPath,agent:r,nativeSessionId:s,sessionKey:`${r}:${s}`,remotePrefix:["projects",t.id,"runtime","sources",o,i].join("/"),localDirectory:vi(t.rootPath,".toolnet","runtime","sources",o,i)}}function Kn(t){return String(t).padStart(12,"0")}var He=class{constructor(e,n=100,r=512*1024){this.storage=e;this.maxEventsPerChunk=n;this.maxChunkBytes=r;if(n<1)throw new Error("maxEventsPerChunk must be positive");if(r<1024)throw new Error("maxChunkBytes is too small")}storage;maxEventsPerChunk;maxChunkBytes;async getJson(e){let n=await this.storage.getText(e);return n?JSON.parse(n):null}async putJson(e,n){await this.storage.put(e,JSON.stringify(n,null,2)+`
|
|
6
6
|
`,"application/json")}async scan(e){let n=`${e.remotePrefix}/events/`,r=await this.storage.list(n),s=[],o=0;for(let i of r){let a=i.key.match(/\/events\/(\d+)-(\d+)-[a-f0-9]+\.jsonl$/);if(!a)continue;let c=Number(a[1]),u=Number(a[2]);!Number.isFinite(c)||!Number.isFinite(u)||(s.push({key:i.key,start:c,end:u}),o=Math.max(o,u))}return s.sort((i,a)=>i.start-a.start),{chunks:s,maxSequence:o}}split(e){let n=[],r=[],s=0;for(let o of e){let i=Buffer.byteLength(JSON.stringify(o)+`
|
|
7
|
-
`,"utf8");r.length>0&&(r.length>=this.maxEventsPerChunk||s+i>this.maxChunkBytes)&&(n.push(r),r=[],s=0),r.push(o),s+=i}return r.length>0&&n.push(r),n}async loadManifest(e){return this.getJson(`${e.remotePrefix}/session.json`)}async loadCursor(e){return this.getJson(`${e.remotePrefix}/cursor.json`)}async recover(e){let n=await this.scan(e);return{maxSequence:n.maxSequence,chunkCount:n.chunks.length}}async append(e,n,r,s={}){let o=await this.loadManifest(e),i=await this.scan(e),a=n.filter(
|
|
7
|
+
`,"utf8");r.length>0&&(r.length>=this.maxEventsPerChunk||s+i>this.maxChunkBytes)&&(n.push(r),r=[],s=0),r.push(o),s+=i}return r.length>0&&n.push(r),n}async loadManifest(e){return this.getJson(`${e.remotePrefix}/session.json`)}async loadCursor(e){return this.getJson(`${e.remotePrefix}/cursor.json`)}async recover(e){let n=await this.scan(e);return{maxSequence:n.maxSequence,chunkCount:n.chunks.length}}async append(e,n,r,s={}){let o=await this.loadManifest(e),i=await this.scan(e),a=n.filter(g=>g.sequence>i.maxSequence),c=0;for(let g of this.split(a)){let y=g[0],v=g[g.length-1],x=g.map(T=>JSON.stringify(T)).join(`
|
|
8
8
|
`)+`
|
|
9
|
-
`,
|
|
10
|
-
`,null,"utf8"),
|
|
11
|
-
`,null,"utf8"),
|
|
9
|
+
`,O=w(x).slice(0,16),P=[e.remotePrefix,"events",`${Kn(y.sequence)}-${Kn(v.sequence)}-${O}.jsonl`].join("/");await this.storage.exists(P)||await this.storage.put(P,x,"application/x-ndjson"),c+=g.length}let u=await this.scan(e),p=n[n.length-1],l=o?.status??"active";p?.type==="session_end"||p?.type==="session_idle"?l="idle":p?.type==="error"?l="error":n.length>0&&(l="active");let f=new Date().toISOString(),d=n[0],m={version:1,projectId:e.projectId,projectName:e.projectName,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,status:l,createdAt:o?.createdAt??d?.timestamp??f,updatedAt:p?.timestamp??f,firstEventAt:o?.firstEventAt??d?.timestamp,lastEventAt:p?.timestamp??o?.lastEventAt,eventCount:u.maxSequence,chunkCount:u.chunks.length,metadata:{...o?.metadata,...s.metadata}};(s.title??o?.title)&&(m.title=s.title??o?.title);let S={version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,lastLocalSequence:n.length>0?n[n.length-1].sequence:u.maxSequence,lastRemoteSequence:u.maxSequence,sourceCursors:r,updatedAt:f};return await this.putJson(`${e.remotePrefix}/cursor.json`,S),await this.putJson(`${e.remotePrefix}/session.json`,m),{uploadedEvents:c,lastRemoteSequence:u.maxSequence,eventCount:m.eventCount,chunkCount:m.chunkCount,status:l}}};import{closeSync as we,existsSync as Ye,fsyncSync as qt,mkdirSync as Ki,openSync as be,readFileSync as Qn,readSync as Fi,rmSync as Un,statSync as Dt,truncateSync as Li,writeSync as Wi}from"node:fs";import{join as zt}from"node:path";var wi=new Set(["thinking","reasoning","reasoningcontent","chainofthought","cot","analysistext","internalreasoning","modelthinking"]),bi=new Set(["reasoning","thinking","chain_of_thought","chain-of-thought","internal_reasoning","internal-reasoning"]);function xi(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function ji(t){for(let e of["type","kind"]){let n=t[e];if(typeof n=="string"){let r=n.toLowerCase();if(bi.has(r))return n}}return null}function $t(t,e=0){if(e>12)return"[ToolNet nested value omitted]";if(Array.isArray(t))return t.map(o=>$t(o,e+1));if(!t||typeof t!="object")return t;let n=t,r=ji(n);if(r)return{type:r,omitted:"[private reasoning omitted]"};let s={};for(let[o,i]of Object.entries(n))wi.has(xi(o))||(s[o]=$t(i,e+1));return s}function Ci(t){if(!t)return new Date().toISOString();let e=new Date(t);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function Y(t){return t?.trim()||void 0}function Fn(t,e={}){let n={...t.provenance??{}},r=Y(t.source)??Y(e.source)??Y(n.source);return{...t,timestamp:Ci(t.timestamp),source:r,turnId:Y(t.turnId)??Y(e.turnId),cwd:Y(t.cwd)??Y(e.cwd),data:$t(t.data??{}),provenance:n}}import{randomUUID as Kt}from"node:crypto";import{closeSync as oe,existsSync as ie,fsyncSync as ke,mkdirSync as Ft,openSync as ve,readFileSync as Lt,readdirSync as Ii,renameSync as Ai,rmSync as Be,statSync as Mi,writeSync as Je}from"node:fs";import{join as B}from"node:path";var Pi=12e4,Ei=80,Oi="reconcile-required";function Ti(t){t<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function ae(t){return B(t,".toolnet","journal")}function Dn(t){return B(ae(t),"events.jsonl")}function Ge(t){return B(ae(t),Oi)}function Ri(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e?.code!=="ESRCH"}}function zn(t){if(!ie(t))return null;try{let e=JSON.parse(Lt(t,"utf8"));return e.version!==1||typeof e.token!="string"||typeof e.pid!="number"||typeof e.acquiredAt!="string"?null:{version:1,token:e.token,pid:e.pid,acquiredAt:e.acquiredAt}}catch{return null}}function Ni(t){if(!ie(t))return!1;let e=0;try{e=Date.now()-Mi(t).mtimeMs}catch{return!1}if(e<=Pi)return!1;let n=zn(t);return n?!Ri(n.pid):!0}function _i(t){if(!Ni(t))return!1;try{return Be(t,{force:!0}),!0}catch{return!1}}function qn(t){for(let e=0;e<Ei;e+=1){let n=Kt();try{let r=ve(t,"wx",384),s={version:1,token:n,pid:process.pid,acquiredAt:new Date().toISOString()};try{return Je(r,`${JSON.stringify(s)}
|
|
10
|
+
`,null,"utf8"),ke(r),{fd:r,token:n}}catch(o){throw oe(r),Be(t,{force:!0}),o}}catch(r){if(r?.code!=="EEXIST")throw r;if(_i(t))continue;Ti(25)}}throw new Error(`Shared project journal is locked: ${t}`)}function Vn(t,e){oe(e.fd),zn(t)?.token===e.token&&Be(t,{force:!0})}function Ln(t){if(!ie(t))return[];let e="";try{e=Lt(t,"utf8")}catch{return[]}let n=[];for(let r of e.split(/\r?\n/)){let s=r.trim();if(s)try{let o=JSON.parse(s);if(o.version!==1||typeof o.id!="string"||o.id.length===0||typeof o.projectId!="string"||o.projectId.length===0)continue;n.push(o)}catch{}}return n}function Hn(t){if(!ie(t))return[];let e=[];for(let n of Ii(t,{withFileTypes:!0})){let r=B(t,n.name);if(n.isDirectory()){e.push(...Hn(r));continue}n.isFile()&&n.name==="events.jsonl"&&e.push(r)}return e.sort()}function Ue(t){let e=null;try{e=ve(t,"r"),ke(e)}catch{}finally{if(e===null)return;oe(e)}}function Wn(t){let e=Ge(t);if(!ie(e))return null;try{return Lt(e,"utf8").trim()||null}catch{return null}}function Wt(t){let e=ae(t);Ft(e,{recursive:!0,mode:448});let n=Ge(t),r=[Kt(),new Date().toISOString()].join("|"),s=ve(n,"w",384);try{Je(s,`${r}
|
|
11
|
+
`,null,"utf8"),ke(s)}finally{oe(s)}Ue(e)}function $i(t,e,n){let r=B(t,`.events.jsonl.tmp-${process.pid}-${Kt()}`),s=ve(r,"w",384);try{let o=n.length===0?"":`${n.map(i=>JSON.stringify(i)).join(`
|
|
12
12
|
`)}
|
|
13
|
-
`;o&&
|
|
13
|
+
`;o&&Je(s,o,null,"utf8"),ke(s)}finally{oe(s)}Ai(r,e),Ue(t)}function Bn(t){let e=ae(t),n=Dn(t),r=B(t,".toolnet","runtime","sources"),s=Wn(t),o=Hn(r),i=[],a=new Set;for(let l of Ln(n))a.has(l.id)||(a.add(l.id),i.push(l));let c=i.length,u=[];for(let l of o)for(let f of Ln(l))a.has(f.id)||(a.add(f.id),u.push(f));u.sort((l,f)=>{let d=l.timestamp.localeCompare(f.timestamp);return d!==0?d:l.id.localeCompare(f.id)}),i.push(...u),$i(e,n,i);let p=Wn(t);return s&&p===s&&(Be(Ge(t),{force:!0}),Ue(e)),{filesScanned:o.length,existingEvents:c,recoveredEvents:u.length,totalEvents:i.length}}function Jn(t){let e=ae(t);Ft(e,{recursive:!0,mode:448});let n=B(e,"journal.lock"),r=qn(n);try{return Bn(t)}finally{Vn(n,r)}}function Gn(t,e){if(e.length===0)return;let n=ae(t);Ft(n,{recursive:!0,mode:448});let r=Dn(t),s=B(n,"journal.lock"),o=qn(s);try{if(ie(Ge(t))){Bn(t);return}let i=`${e.map(c=>JSON.stringify(c)).join(`
|
|
14
14
|
`)}
|
|
15
|
-
`,a=
|
|
16
|
-
`),
|
|
15
|
+
`,a=ve(r,"a",384);try{Je(a,i,null,"utf8"),ke(a)}finally{oe(a)}Ue(n)}finally{Vn(s,o)}}var Di=12e4,zi=80,Yn=2e3;function qi(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Zn(t,e){let n=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"),r=0;for(;r<n.length;){let s=Wi(t,n,r,n.length-r);if(s<=0)throw new Error("Unable to write session WAL");r+=s}}function Vt(t){let e=t.trim();if(!e)return null;try{let n=JSON.parse(e);return n.version!==1||typeof n.id!="string"||!n.id||typeof n.sequence!="number"||!Number.isFinite(n.sequence)||typeof n.projectId!="string"||!n.projectId||typeof n.timestamp!="string"?null:n}catch{return null}}function Vi(t){if(!Ye(t))return[];let e="";try{e=Qn(t,"utf8")}catch{return[]}let n=[];for(let r of e.split(/\r?\n/)){let s=Vt(r);s&&n.push(s)}return n}function Xn(t){return t.type==="session_end"||t.type==="session_idle"?"idle":t.type==="error"?"error":"active"}function Hi(t){if(!Ye(t))return!1;let e;try{e=Qn(t)}catch{return!1}if(e.length===0||e[e.length-1]===10)return!1;let n=e.lastIndexOf(10),r=n>=0?n+1:0,s=e.subarray(r).toString("utf8").trim();if(Vt(s)){let i=be(t,"a");try{Zn(i,`
|
|
16
|
+
`),qt(i)}finally{we(i)}return!0}Li(t,r);let o=be(t,"a");try{qt(o)}finally{we(o)}return!0}function Bi(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}var Xe=class{constructor(e,n={}){this.identity=e;this.eventContext=n;Ki(e.localDirectory,{recursive:!0}),this.eventsFile=zt(e.localDirectory,"events.jsonl"),this.stateFile=zt(e.localDirectory,"state.json"),this.lockFile=zt(e.localDirectory,"journal.lock")}identity;eventContext;eventsFile;stateFile;lockFile;initialState(){let e=new Date().toISOString();return{version:1,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,status:"idle",createdAt:e,updatedAt:e,lastSequence:0,lastRemoteSequence:0,remoteByteOffset:0,sourceCursors:{},recentEventIds:[]}}loadStateUnsafe(){return _n(this.stateFile)??this.initialState()}recoverStateUnsafe(){Hi(this.eventsFile);let e=this.loadStateUnsafe(),n=Vi(this.eventsFile);if(n.length===0)return e;let r=n[0];for(let l of n)l.sequence<=r.sequence||(r=l);let s=n.slice(-Yn).map(l=>l.id),o=Ye(this.eventsFile)?Dt(this.eventsFile).size:0,i=Math.max(e.lastSequence,r.sequence),a=Math.min(e.remoteByteOffset,o),c=r.sequence>e.lastSequence;if(!(c||a!==e.remoteByteOffset||!Bi(e.recentEventIds,s)||e.lastLocalEventAt!==r.timestamp))return e;let p={...e,status:Xn(r),updatedAt:r.timestamp,lastLocalEventAt:r.timestamp,lastSequence:i,remoteByteOffset:a,recentEventIds:s};if(this.saveStateUnsafe(p),!c)return p;try{Wt(this.identity.projectRoot)}catch{return p}try{Jn(this.identity.projectRoot)}catch{}return p}loadState(){return this.withLock(()=>this.recoverStateUnsafe())}saveStateUnsafe(e){R(this.stateFile,e)}acquireLock(){for(let e=0;e<zi;e+=1)try{return be(this.lockFile,"wx",384)}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Dt(this.lockFile).mtimeMs>Di){Un(this.lockFile,{force:!0});continue}}catch{}qi(25)}throw new Error(`Session journal is locked: ${this.lockFile}`)}withLock(e){let n=this.acquireLock();try{return e()}finally{we(n),Un(this.lockFile,{force:!0})}}append(e){return e.length===0?[]:this.withLock(()=>{let n=this.recoverStateUnsafe(),r=new Set(n.recentEventIds),s=n.lastSequence,o=[];for(let l of e){let f=Fn(l,this.eventContext),d=f.timestamp??new Date().toISOString(),m=f.data??{},S=f.provenance?.rawDigest??w(Nn(m)),g=ye(m),y=f.sourceEventId?[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,f.sourceEventId].join("|"):[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,s+1,f.type,d,S].join("|"),v=w(y).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:f.type,timestamp:d,source:f.source??f.provenance?.source??this.identity.agent,data:g,provenance:{...f.provenance,rawDigest:S}};f.role!==void 0&&(x.role=f.role),f.turnId!==void 0&&(x.turnId=f.turnId),f.cwd!==void 0&&(x.cwd=f.cwd),f.sourceEventId!==void 0&&(x.sourceEventId=f.sourceEventId),f.sourceSequence!==void 0&&(x.sourceSequence=f.sourceSequence),o.push(x),r.add(v)}if(o.length===0)return[];let i=o.map(l=>JSON.stringify(l)).join(`
|
|
17
17
|
`)+`
|
|
18
|
-
`,a=
|
|
19
|
-
`)}function
|
|
20
|
-
`),a=Math.max(o,i);return a>r*.7?s.slice(0,a+1):s}function
|
|
21
|
-
`).filter(c=>c.trim());for(let c of a){let u=c.trim();if(u.length<15)continue;let p=u.toLowerCase().replace(/\s+/g," ");if(r.has(p))continue;r.add(p);let l="decision";/\b(rule|quy tắc|policy|standard|convention)\b/i.test(u)||/\b(always|never|must|should|từ giờ|không được)\b/i.test(u)?l="rule":/\b(fix|fixed|bug|issue|error|lỗi)\b/i.test(u)?l="fix":/\b(blocker|blocked|stuck|cannot|không thể)\b/i.test(u)?l="blocker":/\b(next|todo|action|task|cần làm)\b/i.test(u)?l="next_action":/\b(deploy|release|publish|ship)\b/i.test(u)?l="deploy":/\b(architecture|design|structure|pattern)\b/i.test(u)?l="architecture":/\.(ts|js|py|go|rs|java|cpp|c|h)\b/i.test(u)&&(l="file");let f=
|
|
18
|
+
`,a=be(this.eventsFile,"a",384);try{Zn(a,i),qt(a)}finally{we(a)}try{Gn(this.identity.projectRoot,o)}catch{try{Wt(this.identity.projectRoot)}catch{}}let c=o[o.length-1],u=Xn(c),p=Array.from(r).slice(-Yn);return this.saveStateUnsafe({...n,status:u,updatedAt:c.timestamp,lastLocalEventAt:c.timestamp,lastSequence:c.sequence,recentEventIds:p}),o})}readPending(){return this.withLock(()=>{let e=this.recoverStateUnsafe();if(!Ye(this.eventsFile))return{events:[],startOffset:e.remoteByteOffset,endOffset:e.remoteByteOffset};let n=Dt(this.eventsFile).size,r=Math.min(e.remoteByteOffset,n);if(n<=r)return{events:[],startOffset:r,endOffset:n};let s=n-r,o=Buffer.alloc(s),i=be(this.eventsFile,"r");try{Fi(i,o,0,s,r)}finally{we(i)}let a=[];for(let c of o.toString("utf8").split(/\r?\n/)){let u=Vt(c);u&&a.push(u)}return{events:a,startOffset:r,endOffset:n}})}markRemote(e,n){this.withLock(()=>{let r=this.recoverStateUnsafe(),s=new Date().toISOString();this.saveStateUnsafe({...r,lastRemoteSequence:Math.max(r.lastRemoteSequence,e),remoteByteOffset:Math.max(r.remoteByteOffset,n),lastRemoteAt:s,updatedAt:s})})}setSourceCursor(e,n){this.withLock(()=>{let r=this.recoverStateUnsafe();this.saveStateUnsafe({...r,sourceCursors:{...r.sourceCursors,[e]:String(n)},updatedAt:new Date().toISOString()})})}};import{closeSync as Wc,existsSync as Dc,openSync as zc,readSync as qc,statSync as Vc}from"node:fs";var Ji=new Set(["rule","blocker","architecture","deploy"]),Gi=new Set(["fix","todo","context","next_action"]);function Ht(t){return t<0?0:t>1?1:t}function er(t,e){let n=Number.parseFloat(t??"");return Number.isFinite(n)?n:e}function Ui(t){return t==="off"?"off":t==="balanced"?"balanced":t==="aggressive"?"aggressive":"conservative"}function Bt(){return{mode:Ui(process.env.TOOLNET_MEMORY_PROMOTION),minScore:Ht(er(process.env.TOOLNET_PROMOTE_MIN_SCORE,.65)),minConfidence:Ht(er(process.env.TOOLNET_PROMOTE_MIN_CONFIDENCE,.78))}}function Yi(t){switch(t){case"critical":return 1;case"high":return .85;case"normal":return .6;case"temporary":return .25}}function Xi(t){let e=Ht(Yi(t.importance)*.75+t.confidence*.25);return Math.round(e*1e6)/1e6}function Qi(t){return t.evidence?t.evidence:{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1}}function Zi(t,e=Bt()){if(t.importance==="temporary"||t.confidence<e.minConfidence)return"transient";let n=Qi(t);return t.kind==="rule"&&n.userExplicit?"permanent":t.kind==="rule"?"session":t.kind==="architecture"&&(n.userExplicit||n.sourceVerified||n.testVerified||n.crossSessionConfirmations>=2)?"permanent":t.kind==="architecture"?"session":t.kind==="decision"||t.kind==="todo"||t.kind==="fix"?"task":"session"}function ea(t,e=Bt()){if(e.mode==="off")return Number.POSITIVE_INFINITY;let n=0;e.mode==="balanced"&&(n=.1),e.mode==="aggressive"&&(n=.15);let r=Math.max(e.mode==="aggressive"?.5:.55,e.minScore-n);return Ji.has(t)&&(r=Math.max(.5,r-.1)),Gi.has(t)&&(r=Math.max(.5,r-.05)),r}function Jt(t,e=Bt()){let n=Zi(t,e),r=Xi(t),s=ea(t.kind,e);return n==="transient"?{knowledgeClass:n,score:r,threshold:s,persist:!1}:e.mode==="off"?{knowledgeClass:n,score:r,threshold:s,persist:!1}:{knowledgeClass:n,score:r,threshold:s,persist:r>=s}}function tr(t,e){let n=e.toLowerCase();return n.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||n.includes("tuy\u1EC7t \u0111\u1ED1i")||n.includes("must not")||n.includes("never ")?"critical":t==="rule"||t==="decision"?"high":t==="todo"||n.includes("error")||n.includes("failed")||n.includes("exception")?"normal":"temporary"}var 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],ta=[/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],na=[/\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],ra=[/\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],sa=[/đã 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],nr=[/kiến trúc/iu,/pipeline/iu,/adapter/iu,/schema/iu,/runtime/iu,/namespace/iu,/storage/iu,/lưu trữ/iu,/workflow/iu,/session core/iu,/memory engine/iu,/retrieval/iu],oa=[/\bdùng\b/iu,/\btách\b/iu,/\bthay\b/iu,/\bchuyển\b/iu,/\blưu\b/iu,/\bmap\b/iu,/\buse\b/iu,/\bsplit\b/iu,/\bstore\b/iu,/\breplace\b/iu,/\bmove\b/iu],ia=[/đườ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],aa=[/\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],rr=new Set(["content","text","message","prompt","summary","description","reason","title","last_assistant_message","lastAssistantMessage","input_messages","inputMessages"]),ca=new Set(["payload","data","content","message","messages","parts","summary"]);function N(t,e){return e.some(n=>n.test(t))}function ir(t){return t.normalize("NFKC").replace(/\r/g,"").replace(/^[\s>*#\-•]+/u,"").replace(/\s+/g," ").trim()}function ua(t){return ir(t).toLowerCase().replace(/[^\p{L}\p{N}:/._-]+/gu," ").replace(/\s+/g," ").trim()}function la(t){return!(t.length<12||t.length>1e3||(t.match(new RegExp("\\p{L}","gu"))??[]).length<6||/^(?:https?:\/\/\S+|[A-Za-z0-9+/=]{80,})$/u.test(t))}function Gt(t,e,n,r=0){if(!(r>6)&&!(typeof t=="string"&&e&&!rr.has(e))){if(typeof t=="string"){n.push(t);return}if(Array.isArray(t)){for(let s of t.slice(0,50))Gt(s,e,n,r+1);return}if(!(!t||typeof t!="object"))for(let[s,o]of Object.entries(t))(rr.has(s)||ca.has(s))&&Gt(o,s,n,r+1)}}function da(t){let e=[];Gt(t.data,void 0,e);let n=[],r=new Set;for(let s of e)for(let o of s.split(/\n+|(?<=[.!?])\s+/u)){let i=ir(o);if(la(i)&&!r.has(i)&&(r.add(i),n.push(i),n.length>=50))return n}return n}function sr(t){return(t.role??(typeof t.data.role=="string"?t.data.role:"")).toLowerCase()}function pa(t,e,n){if(n.type==="decision")return{kind:"decision",confidence:1};if(n.type==="todo")return{kind:"todo",confidence:1};let r=e==="user"||n.type==="user_prompt",s=e==="assistant"||n.type==="assistant_message";return r&&N(t,or)?{kind:"rule",confidence:.98}:r&&N(t,ta)?{kind:"rule",confidence:.92}:N(t,na)?{kind:N(t,nr)?"architecture":"decision",confidence:r?.93:.86}:r&&N(t,ra)?{kind:"todo",confidence:.87}:N(t,nr)&&N(t,oa)?{kind:"architecture",confidence:r?.88:.82}:s&&N(t,sa)?{kind:"fix",confidence:.8}:r&&N(t,ia)&&N(t,aa)?{kind:"context",confidence:.79}:null}function fa(t,e,n){let r=e==="user"||n.type==="user_prompt",s=e==="assistant"||n.type==="assistant_message",o=!!n.provenance.sourcePath&&(t==="architecture"||t==="context"||t==="fix"),i=t==="fix"&&/(?:test|tests|pass|passed|passing)/iu.test(JSON.stringify(n.data));return{userExplicit:r,sourceVerified:o,testVerified:i,crossSessionConfirmations:1,assistantDerived:s}}function ma(t){switch(t){case"rule":return"rule";case"decision":case"architecture":return"decision";case"todo":return"todo";case"fix":case"context":return"code"}}function ga(t,e,n){return t==="rule"&&N(n,or)?"critical":t==="architecture"||t==="decision"||t==="rule"?"high":t==="fix"||t==="context"?"normal":tr(e,n)}function ar(t,e){let n=[],r=new Set,s=new Map;for(let o of e){let i=typeof o.data.messageId=="string"?o.data.messageId:void 0,a=sr(o);i&&a&&s.set(i,a)}for(let o of e){let i=sr(o),a=typeof o.data.messageId=="string"?o.data.messageId:void 0;!i&&a&&(i=s.get(a)??"");for(let c of da(o)){let u=pa(c,i,o);if(!u||u.confidence<.75)continue;let p=ma(u.kind),l=ua(c),f=w([t.projectId,u.kind,l].join("|"));if(r.has(f))continue;r.add(f);let d=o.provenance.sourcePath?[o.provenance.sourcePath]:[],m=o.sourceEventId?[o.sourceEventId]:[];n.push({version:1,fingerprint:f,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,kind:u.kind,type:p,content:c,confidence:u.confidence,importance:ga(u.kind,p,c),evidence:fa(u.kind,i,o),tags:[p],provenance:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,eventIds:[o.id],sourceEventIds:m,sourcePaths:d,firstSequence:o.sequence,lastSequence:o.sequence},createdAt:o.timestamp})}}return n}import{createHash as ya}from"node:crypto";var ha=["project-knowledge","implementation","continuation","session-context"],Sa={"project-knowledge":"Project knowledge",implementation:"Implementation state",continuation:"Work continuation","session-context":"Session context"};function Ut(t){return ya("sha256").update(t).digest("hex")}function Qe(t,e){return`${t}:${Ut(e).slice(0,24)}`}function ka(t){try{return Ut(JSON.stringify(t))}catch{return Ut(String(t))}}function X(t){let e=new Set,n=[];for(let r of t){let s=r?.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function ur(t,e=420){let n=t.replace(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1)).trimEnd()}\u2026`}function va(t){return t==="rule"||t==="architecture"?"project-knowledge":t==="decision"||t==="fix"?"implementation":t==="todo"?"continuation":"session-context"}function cr(t){return t.length===0?0:t.reduce((e,n)=>e+n,0)/t.length}function wa(t){return t.slice().sort((e,n)=>n.importanceScore-e.importanceScore||n.confidence-e.confidence||e.id.localeCompare(n.id)).slice(0,5).map(e=>ur(e.content)).join(" | ")}function ba(t){return t.slice().sort((e,n)=>n.importanceScore-e.importanceScore||n.confidence-e.confidence||e.id.localeCompare(n.id)).slice(0,6).map(e=>ur(e.content)).join(`
|
|
19
|
+
`)}function lr(t,e){let n=t.slice().sort((f,d)=>f.sequence-d.sequence||f.timestamp.localeCompare(d.timestamp)||f.id.localeCompare(d.id)),r=n.map(f=>({id:Qe("raw",[f.projectId,f.agent,f.nativeSessionId,f.id,String(f.sequence)].join("|")),level:"raw",eventId:f.id,sourceEventId:f.sourceEventId,sequence:f.sequence,type:f.type,role:f.role,timestamp:f.timestamp,sourcePath:f.provenance.sourcePath,payloadDigest:ka(f.data)})),s=new Map,o=new Map;n.forEach((f,d)=>{let m=r[d];m&&(s.set(f.id,m.id),f.sourceEventId&&o.set(f.sourceEventId,m.id))});let i=e.map(f=>{let d=X([...f.provenance.eventIds.map(m=>s.get(m)),...f.provenance.sourceEventIds.map(m=>o.get(m))]);return{id:Qe("fact",f.fingerprint),level:"fact",fingerprint:f.fingerprint,kind:f.kind,type:f.type,content:f.content,knowledgeClass:f.knowledgeClass,importanceScore:f.importanceScore,confidence:f.confidence,tags:X([...f.tags,"level:fact",`class:${f.knowledgeClass}`,`kind:${f.kind}`]),rawIds:d,sourcePaths:X(f.provenance.sourcePaths)}}),a=new Map;for(let f of i){let d=va(f.kind),m=a.get(d)??[];m.push(f),a.set(d,m)}let c=[];for(let f of ha){let d=a.get(f);if(!d?.length)continue;let m=d.slice().sort((g,y)=>y.importanceScore-g.importanceScore||y.confidence-g.confidence||g.id.localeCompare(y.id)),S=m.map(g=>g.id);c.push({id:Qe("scene",`${f}|${S.join("|")}`),level:"scene",kind:f,title:Sa[f],summary:wa(m),factIds:S,importanceScore:Math.max(...m.map(g=>g.importanceScore)),confidence:cr(m.map(g=>g.confidence)),tags:X(["level:scene",`scene:${f}`,...m.flatMap(g=>g.tags)]),sourcePaths:X(m.flatMap(g=>g.sourcePaths))})}let u=new Map(i.map(f=>[f.id,f])),p=[];for(let f of c){let m=f.factIds.map(y=>u.get(y)).filter(y=>!!y).filter(y=>(y.knowledgeClass==="permanent"||y.knowledgeClass==="task")&&y.importanceScore>=.55);if(m.length===0)continue;let S=m.some(y=>y.knowledgeClass==="permanent")?"permanent":"task",g=ba(m);p.push({id:Qe("knowledge",`${f.id}|${S}|${m.map(y=>y.id).join("|")}`),level:"knowledge",knowledgeClass:S,title:f.title,content:g,sceneIds:[f.id],factIds:m.map(y=>y.id),importanceScore:Math.max(...m.map(y=>y.importanceScore)),confidence:cr(m.map(y=>y.confidence)),tags:X(["level:knowledge",`class:${S}`,`scene:${f.kind}`,...m.flatMap(y=>y.tags)]),sourcePaths:X(m.flatMap(y=>y.sourcePaths))})}let l=[];for(let f of i)for(let d of f.rawIds)l.push({from:d,to:f.id,type:"supports"});for(let f of c)for(let d of f.factIds)l.push({from:d,to:f.id,type:"belongs_to"});for(let f of p)for(let d of f.sceneIds)l.push({from:d,to:f.id,type:"promotes_to"});return{schema:"toolnet.memory-hierarchy.v1",version:1,raw:r,facts:i,scenes:c,knowledge:p,links:l,stats:{raw:r.length,facts:i.length,scenes:c.length,knowledge:p.length,links:l.length}}}function Ze(t){return t?Math.ceil(t.length/3.5):0}function et(t,e){if(!t)return"";if(Ze(t)<=e)return t;let r=Math.floor(e*3.5),s=t.slice(0,r),o=s.lastIndexOf("."),i=s.lastIndexOf(`
|
|
20
|
+
`),a=Math.max(o,i);return a>r*.7?s.slice(0,a+1):s}function Q(){let t=Ke(),e=process.env.TOOLNET_SESSION_SAVE||"summary",n=process.env.TOOLNET_RAW_TRANSCRIPT==="on"||e==="archive"||e==="full",r=process.env.TOOLNET_MEMORY_PROMOTION||"conservative",s=parseFloat(process.env.TOOLNET_PROMOTE_MIN_SCORE||"0.65"),o=parseInt(process.env.TOOLNET_SESSION_SUMMARY_MAX_TOKENS||"700",10),i=parseInt(process.env.TOOLNET_DURABLE_MEMORY_MAX_ITEMS_PER_SESSION||"10",10),a=n,c=process.env.TOOLNET_RAW_TRANSCRIPT_REMOTE==="on"||e==="full";return{sessionSave:e,rawTranscript:n,memoryPromotion:r,promoteMinScore:s,sessionSummaryMaxTokens:o,durableMemoryMaxItemsPerSession:i,archiveLocal:a,archiveRemote:c}}function dr(t){return(t||Q()).rawTranscript}function pr(t){return(t||Q()).durableMemoryMaxItemsPerSession}function fr(t){return(t||Q()).sessionSummaryMaxTokens}function mr(t){return(t||Q()).archiveRemote}var gr=new H;function yr(t){let e=t.trim();if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{let r=JSON.parse(e);return JSON.stringify(gr.sanitizeValue(r))}catch{}let n=gr.sanitize(t).text;return n=n.replace(/("(?:api[_-]?key|token|secret|password|cookie|authorization)"\s*:\s*)"[^"]*"/gi,'$1"[REDACTED]"').replace(/('(?:api[_-]?key|token|secret|password|cookie|authorization)'\s*:\s*)'[^']*'/gi,"$1'[REDACTED]'").replace(/\b(api[_-]?key|token|secret|password|cookie|authorization)\b\s*[:=]\s*[^\s,;]+/gi,"$1=[REDACTED]").replace(/\bbearer\s+[A-Za-z0-9._~+/=-]+/gi,"Bearer [REDACTED]"),n}function xa(t,e){let n=t.toLowerCase(),r=.5,s=["nh\u1EDB","remember","quy t\u1EAFc","rule","t\u1EEB gi\u1EDD","from now","kh\xF4ng \u0111\u01B0\u1EE3c","must not","lu\xF4n lu\xF4n","always","never","critical","important","blocker","deploy","production","architecture"];for(let i of s)n.includes(i)&&(r+=.15);e==="rule"||e==="architecture"||e==="blocker"?r+=.2:e==="decision"||e==="deploy"?r+=.15:(e==="fix"||e==="next_action")&&(r+=.1),t.length<20?r-=.3:t.length>500&&(r-=.1);let o=[/npm (notice|warn|ERR)/i,/\d+ packages? in \d+/i,/found \d+ vulnerabilities/i,/up to date/i,/added \d+ packages/i,/^(ok|done|success|error|warning)$/i];for(let i of o)i.test(t)&&(r-=.4);return Math.max(0,Math.min(1,r))}function ja(t,e){let n=[],r=new Set;for(let i of t){let a=i.split(`
|
|
21
|
+
`).filter(c=>c.trim());for(let c of a){let u=c.trim();if(u.length<15)continue;let p=u.toLowerCase().replace(/\s+/g," ");if(r.has(p))continue;r.add(p);let l="decision";/\b(rule|quy tắc|policy|standard|convention)\b/i.test(u)||/\b(always|never|must|should|từ giờ|không được)\b/i.test(u)?l="rule":/\b(fix|fixed|bug|issue|error|lỗi)\b/i.test(u)?l="fix":/\b(blocker|blocked|stuck|cannot|không thể)\b/i.test(u)?l="blocker":/\b(next|todo|action|task|cần làm)\b/i.test(u)?l="next_action":/\b(deploy|release|publish|ship)\b/i.test(u)?l="deploy":/\b(architecture|design|structure|pattern)\b/i.test(u)?l="architecture":/\.(ts|js|py|go|rs|java|cpp|c|h)\b/i.test(u)&&(l="file");let f=xa(u,l);if(f<.3)continue;let d=yr(u);n.push({category:l,text:d,importance:f,sourceSessionId:e})}}let s=Q(),o=pr(s);return n.sort((i,a)=>a.importance-i.importance).slice(0,o)}function Ca(t){let e=Q(),n=fr(e),o=t.join(`
|
|
22
22
|
|
|
23
23
|
`).split(`
|
|
24
|
-
`).filter(i=>{let a=i.trim();return a.length>20&&!a.startsWith("npm")&&!a.startsWith("\u2713")&&!a.startsWith("Error:")}).slice(0,20).map(i=>
|
|
25
|
-
`);return
|
|
24
|
+
`).filter(i=>{let a=i.trim();return a.length>20&&!a.startsWith("npm")&&!a.startsWith("\u2713")&&!a.startsWith("Error:")}).slice(0,20).map(i=>yr(i)).join(`
|
|
25
|
+
`);return et(o,n)}function tt(t,e){let r=(Array.isArray(t)?t:t.split(`
|
|
26
26
|
|
|
27
|
-
`).filter(d=>d.trim())).map(d=>typeof d=="string"?d:JSON.stringify(d)).filter(d=>d.trim()),s=
|
|
28
|
-
`)}function
|
|
29
|
-
`;Fa(Ze(Ea(t),`${c}.json`),p)?s+=1:o+=1,i.push(c),n=Wa(n,{id:c,kind:a.type,bytes:Buffer.byteLength(p,"utf8"),createdAt:a.timestamp,sourceRefs:[Ka(a)],files:$a(a)})}return r>0&&Na(t,n),{eligible:r,written:s,deduped:o,graphNodes:n.nodes.length,assetIds:i}}import{createHash as Va}from"node:crypto";import{existsSync as Ga,readdirSync as Ua,readFileSync as Ya}from"node:fs";import{basename as Xa,join as Nr}from"node:path";import{randomUUID as vr}from"node:crypto";var C=class extends Error{constructor(n,r){super(n);this.statusCode=r}statusCode};function we(t){let e=new Set,n=[];for(let r of t){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function Z(t){let e=t.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,120);if(!e)throw new C("Invalid Wiki slug",400);return e}function Sr(t){let e=[];for(let n of t.matchAll(/\[\[([^\[\]]+)\]\]/gu)){let r=n[1]?.trim();r&&e.push(Z(r))}return we(e)}function La(t){return t.normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}_-]+/u).map(e=>e.trim()).filter(e=>e.length>=2)}function kr(t){return{id:`revision-${vr()}`,pageId:t.id,slug:t.slug,revision:t.revision,title:t.title,...t.summary?{summary:t.summary}:{},content:t.content,tags:[...t.tags],links:[...t.links],createdAt:t.updatedAt}}function Q(t){return structuredClone(t)}var et=class{constructor(e){this.store=e}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}async mutate(e){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=e(s),s.updatedAt=new Date().toISOString(),await this.store.save(s)});return this.queue=r.then(()=>{},()=>{}),await r,n}async summary(){let e=await this.ensureState(),n=new Set(e.pages.flatMap(r=>r.links));return{schema:"toolnet.wiki-summary.v1",projectId:e.projectId,pages:e.pages.length,revisions:e.revisions.length,tags:we(e.pages.flatMap(r=>r.tags)).sort((r,s)=>r.localeCompare(s)),links:e.pages.reduce((r,s)=>r+s.links.length,0),orphanPages:e.pages.filter(r=>r.links.length===0&&!n.has(r.slug)).length,automatedPages:e.pages.filter(r=>r.tags.some(s=>s.startsWith("toolnet-auto-"))).length,updatedAt:e.updatedAt}}async listPages(){let e=await this.ensureState();return Q([...e.pages].sort((n,r)=>n.title.localeCompare(r.title)))}async getPage(e){let n=await this.ensureState(),r=Z(e),s=n.pages.find(o=>o.slug===r||o.id===e);if(!s)throw new C(`Wiki page not found: ${e}`,404);return Q(s)}async createPage(e){return this.mutate(n=>{let r=e.title.trim(),s=e.content.trim();if(!r)throw new C("Wiki title is required",400);let o=Z(e.slug??r);if(n.pages.some(c=>c.slug===o))throw new C(`Wiki page already exists: ${o}`,409);let i=new Date().toISOString(),a={id:`wiki-${vr()}`,slug:o,title:r,...e.summary?.trim()?{summary:e.summary.trim()}:{},content:s,tags:we(e.tags??[]),links:Sr(s),revision:1,createdAt:i,updatedAt:i};return n.pages.push(a),n.revisions.push(kr(a)),Q(a)})}async updatePage(e,n){return this.mutate(r=>{let s=Z(e),o=r.pages.find(i=>i.slug===s||i.id===e);if(!o)throw new C(`Wiki page not found: ${e}`,404);if(n.title!==void 0){let i=n.title.trim();if(!i)throw new C("Wiki title is required",400);o.title=i}if(n.summary!==void 0){let i=n.summary.trim();i?o.summary=i:delete o.summary}return n.content!==void 0&&(o.content=n.content.trim(),o.links=Sr(o.content)),n.tags!==void 0&&(o.tags=we(n.tags)),o.revision+=1,o.updatedAt=new Date().toISOString(),r.revisions.push(kr(o)),Q(o)})}async history(e){let n=await this.getPage(e),r=await this.ensureState();return Q(r.revisions.filter(s=>s.pageId===n.id).sort((s,o)=>o.revision-s.revision))}async backlinks(e){let n=await this.getPage(e),r=await this.ensureState();return Q(r.pages.filter(s=>s.links.includes(n.slug)).sort((s,o)=>s.title.localeCompare(o.title)))}async search(e,n=10){let r=await this.ensureState(),s=we(La(e));if(s.length===0)return[];let o=Math.max(1,Math.min(20,Math.floor(n))),i=[];for(let a of r.pages){let c=a.title.toLowerCase(),u=a.slug.toLowerCase(),p=a.summary?.toLowerCase()??"",l=a.content.toLowerCase(),f=a.tags.map(g=>g.toLowerCase()),d=0;for(let g of s)u===g&&(d+=12),c===g&&(d+=10),c.includes(g)&&(d+=6),u.includes(g)&&(d+=5),f.some(S=>S===g)?d+=5:f.some(S=>S.includes(g))&&(d+=3),p.includes(g)&&(d+=2),l.includes(g)&&(d+=1);d>0&&i.push({page:Q(a),score:d})}return i.sort((a,c)=>c.score-a.score||c.page.updatedAt.localeCompare(a.page.updatedAt)).slice(0,o)}};var wr="wiki/state.v1.json";function Da(t){let e=new Date().toISOString();return{schema:"toolnet.wiki.v1",version:1,projectId:t.id,pages:[],revisions:[],createdAt:e,updatedAt:e}}function za(t,e){let n=JSON.parse(t);if(n.schema!=="toolnet.wiki.v1"||n.version!==1||n.projectId!==e.id||!Array.isArray(n.pages)||!Array.isArray(n.revisions))throw new Error("Invalid ToolNet Wiki state");return n}var tt=class{constructor(e,n){this.storage=e;this.project=n}storage;project;async load(){let e=await this.storage.getText(wr);if(!e){let n=Da(this.project);return await this.save(n),n}return za(e,this.project)}async save(e){await this.storage.put(wr,JSON.stringify(e,null,2),"application/json")}};import{createHash as qa,randomUUID as br}from"node:crypto";var xr="wiki/governance.v1.json",Ar="toolnet.knowledge-governance.v1",jr=500,be={autoApproveThreshold:.86,criticalApproveThreshold:.94,staleAfterDays:90};function Ba(t,e=0,n=1){return Math.max(e,Math.min(n,t))}function Yt(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function Cr(t){return qa("sha256").update(t.normalize("NFKC").replace(/\s+/gu," ").trim()).digest("hex")}function Ja(t){let e=[t.title,t.summary??"",t.content.slice(0,2e3),...t.tags].join(" ").toLowerCase();return/\b(?:architecture|security|authentication|authorization|auth|database|production|deploy|deployment|payment|billing|permission|permissions|acl|credential|secret|migration)\b/u.test(e)}function Ha(t){let e=t.sourceType==="skill"?.96:t.sourceType==="memory"?.94:.88,n=t.tags.map(r=>r.toLowerCase());return(n.includes("permanent")||n.includes("task"))&&(e+=.03),t.content.length>=200&&(e+=.02),t.content.length<80&&(e-=.05),t.title.length<4&&(e-=.05),Ba(e)}function Ir(t){let e=new Date().toISOString();return{schema:Ar,version:1,projectId:t,policy:{...be},reviews:[],audit:[],createdAt:e,updatedAt:e}}function Mr(t){let e=t.autoApproveThreshold??be.autoApproveThreshold,n=t.criticalApproveThreshold??be.criticalApproveThreshold,r=t.staleAfterDays??be.staleAfterDays;if(!Number.isFinite(e)||e<.5||e>1)throw new C("Invalid autoApproveThreshold",400);if(!Number.isFinite(n)||n<.5||n>1)throw new C("Invalid criticalApproveThreshold",400);if(!Number.isInteger(r)||r<1||r>3650)throw new C("Invalid staleAfterDays",400);return{autoApproveThreshold:e,criticalApproveThreshold:n,staleAfterDays:r}}var nt=class{constructor(e,n){this.storage=e;this.project=n}storage;project;async load(){let e=await this.storage.getText(xr);if(!e){let n=Ir(this.project.id);return await this.save(n),n}try{let n=JSON.parse(e);if(n.schema!==Ar||n.version!==1||n.projectId!==this.project.id||!Array.isArray(n.reviews)||!Array.isArray(n.audit))throw new Error("invalid");return{...n,policy:Mr(n.policy??be)}}catch{let n=Ir(this.project.id);return await this.save(n),n}}async save(e){await this.storage.put(xr,JSON.stringify(e,null,2),"application/json")}},rt=class{constructor(e){this.store=e}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}audit(e,n,r,s={}){e.audit.push({id:br(),action:n,principal:r,...s.reviewId?{reviewId:s.reviewId}:{},...s.sourceKey?{sourceKey:s.sourceKey}:{},timestamp:new Date().toISOString(),...s.metadata?{metadata:s.metadata}:{}}),e.audit.length>jr&&(e.audit=e.audit.slice(-jr))}async mutate(e){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=await e(s),s.updatedAt=new Date().toISOString(),await this.store.save(s)});return this.queue=r.then(()=>{},()=>{}),await r,n}async policy(){return{...(await this.ensureState()).policy}}async setPolicy(e,n){return this.mutate(r=>(r.policy=Mr({...r.policy,...e}),this.audit(r,"policy:update",n,{metadata:{...r.policy}}),{...r.policy}))}async summary(){let e=await this.ensureState(),n=r=>e.reviews.filter(s=>s.status===r).length;return{schema:"toolnet.knowledge-governance-summary.v1",projectId:e.projectId,pending:n("pending"),approved:n("approved"),rejected:n("rejected"),superseded:n("superseded"),criticalPending:e.reviews.filter(r=>r.status==="pending"&&r.risk==="critical").length,conflictPending:e.reviews.filter(r=>r.status==="pending"&&r.risk==="conflict").length,auditEvents:e.audit.length,policy:{...e.policy},updatedAt:e.updatedAt}}async listReviews(e){let n=await this.ensureState();return structuredClone(n.reviews.filter(r=>!e||r.status===e).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt)))}async auditLog(e=100){let n=await this.ensureState(),r=Math.max(1,Math.min(500,Math.floor(e)));return structuredClone(n.audit.slice(-r).reverse())}async assess(e,n){let r=await this.ensureState(),s=Ha(e),o=Yt(e.title),i=n.filter(p=>p.slug!==e.slug&&Yt(p.title)===o&&Cr(p.content)!==Cr(e.content)).map(p=>p.slug),a=Ja(e),c=[];s<r.policy.autoApproveThreshold&&c.push(`confidence:${s.toFixed(2)}`),a&&s<r.policy.criticalApproveThreshold&&c.push("critical-knowledge"),i.length>0&&c.push("conflicting-knowledge");let u=i.length>0?"conflict":a?"critical":"normal";return{confidence:s,risk:u,requiresReview:i.length>0||s<r.policy.autoApproveThreshold||a&&s<r.policy.criticalApproveThreshold,reasons:c,conflicts:i}}async gate(e,n){let r=await this.assess(e,n);return this.mutate(s=>{let o=s.reviews.find(c=>c.sourceKey===e.sourceKey&&c.digest===e.digest);if(o?.status==="approved")return{allowed:!0,mode:"review-approved",assessment:r,review:structuredClone(o)};if(o?.status==="rejected")return{allowed:!1,mode:"rejected",assessment:r,review:structuredClone(o)};if(!r.requiresReview)return this.audit(s,"knowledge:auto-approved","system",{sourceKey:e.sourceKey,metadata:{confidence:r.confidence,risk:r.risk}}),{allowed:!0,mode:"auto-approved",assessment:r};if(o?.status==="pending")return{allowed:!1,mode:"pending-review",assessment:r,review:structuredClone(o)};let i=new Date().toISOString(),a={id:br(),sourceKey:e.sourceKey,sourceType:e.sourceType,slug:e.slug,marker:e.marker,digest:e.digest,title:e.title,...e.summary?{summary:e.summary}:{},content:e.content,tags:[...new Set([...e.tags,e.marker])],confidence:r.confidence,risk:r.risk,reasons:[...r.reasons],conflicts:[...r.conflicts],status:"pending",createdAt:i,updatedAt:i};return s.reviews.push(a),this.audit(s,"knowledge:review-requested","system",{reviewId:a.id,sourceKey:a.sourceKey,metadata:{confidence:a.confidence,risk:a.risk}}),{allowed:!1,mode:"pending-review",assessment:r,review:structuredClone(a)}})}async markApplied(e,n){await this.mutate(r=>{let s=r.reviews.find(o=>o.sourceKey===e&&o.digest===n&&o.status==="approved");s&&(s.appliedAt=new Date().toISOString(),s.updatedAt=s.appliedAt,this.audit(r,"knowledge:applied",s.reviewedBy??"system",{reviewId:s.id,sourceKey:e}))})}async decide(e,n,r){return this.mutate(async s=>{let o=s.reviews.find(u=>u.id===e);if(!o)throw new C(`Governance review not found: ${e}`,404);if(o.status!=="pending")throw new C("Governance review is already resolved",409);let i=new Date().toISOString();if(o.reviewedAt=i,o.reviewedBy=n.principal,o.updatedAt=i,n.note?.trim()&&(o.reviewNote=n.note.trim()),n.action==="reject")return o.status="rejected",this.audit(s,"knowledge:rejected",n.principal,{reviewId:e,sourceKey:o.sourceKey}),structuredClone(o);if(n.action==="supersede")return o.status="superseded",n.targetReviewId&&(o.supersededBy=n.targetReviewId),this.audit(s,"knowledge:superseded",n.principal,{reviewId:e,sourceKey:o.sourceKey,metadata:{targetReviewId:n.targetReviewId}}),structuredClone(o);if(n.action==="merge"){if(!n.targetReviewId)throw new C("targetReviewId is required for merge",400);let u=s.reviews.find(p=>p.id===n.targetReviewId);if(!u)throw new C("Merge target review not found",404);return o.status="superseded",o.mergedInto=u.id,this.audit(s,"knowledge:merged",n.principal,{reviewId:e,sourceKey:o.sourceKey,metadata:{targetReviewId:u.id}}),structuredClone(o)}o.status="approved";let c=(await r.listPages()).find(u=>u.slug===o.slug);if(c&&!c.tags.includes(o.marker))throw new C(`Wiki page '${o.slug}' is manually managed`,409);return c?await r.updatePage(o.slug,{title:o.title,summary:o.summary??"",content:o.content,tags:o.tags}):await r.createPage({slug:o.slug,title:o.title,...o.summary?{summary:o.summary}:{},content:o.content,tags:o.tags}),o.appliedAt=i,this.audit(s,"knowledge:approved",n.principal,{reviewId:e,sourceKey:o.sourceKey}),structuredClone(o)})}async quality(e){let n=await this.ensureState(),r=await e.listPages(),s=Date.now(),o=n.policy.staleAfterDays*864e5,i=r.map(p=>{let l=s-Date.parse(p.updatedAt);return{slug:p.slug,title:p.title,updatedAt:p.updatedAt,ageDays:Math.max(0,Math.floor(l/864e5)),stale:Number.isFinite(l)&&l>o}}).filter(p=>p.stale).map(({stale:p,...l})=>l),a=new Map;for(let p of r){let l=Yt(p.title),f=a.get(l)??[];f.push(p),a.set(l,f)}let c=[...a.entries()].filter(([,p])=>p.length>1).map(([p,l])=>({title:p,pages:l.map(f=>f.slug)})),u=n.reviews.filter(p=>p.status==="pending");return{schema:"toolnet.knowledge-quality.v1",totalPages:r.length,automatedPages:r.filter(p=>p.tags.some(l=>l.startsWith("toolnet-auto-"))).length,manualPages:r.filter(p=>!p.tags.some(l=>l.startsWith("toolnet-auto-"))).length,stalePages:i,duplicateTitles:c,pendingReviews:u.length,lowConfidenceReviews:u.filter(p=>p.confidence<n.policy.autoApproveThreshold).length,conflicts:u.filter(p=>p.risk==="conflict").length,generatedAt:new Date().toISOString()}}};var _r="wiki/automation.v1.json",$r="toolnet.wiki-automation.v1",Zt=8e3,Pr=new Set(["raw","rawtext","raw_text","rawtranscript","raw_transcript","transcript","messages","message","payload","prompt","response","assistantmessage","assistant_message","userprompt","user_prompt"]);function je(t){return Va("sha256").update(JSON.stringify(t)).digest("hex")}function xe(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Er(t){return Array.isArray(t)?t:[]}function Kr(t){return typeof t!="string"?void 0:t.replace(/\s+/gu," ").trim()||void 0}function Xt(t){return Array.isArray(t)?t.map(Kr).filter(e=>!!e):[]}function $(t,e){for(let n of e){let r=Kr(t[n]);if(r)return r}}function Ce(t){let e=new Set,n=[];for(let r of t){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function st(t,e=0,n=""){if(e>3)return[];let r=n.replace(/[^a-z0-9]/giu,"").toLowerCase();if(Pr.has(r))return[];if(typeof t=="string"){let i=t.replace(/\s+/gu," ").trim();return i.length<8?[]:[i]}if(Array.isArray(t))return t.flatMap(i=>st(i,e+1,n));let s=xe(t);if(!s)return[];let o=[];for(let[i,a]of Object.entries(s)){let c=i.replace(/[^a-z0-9]/giu,"").toLowerCase();Pr.has(c)||o.push(...st(a,e+1,i))}return o}function Or(t){let n=Ce(["content","summary","text","value","statement","description","decision","task","knowledge","context","outcome","reason","rationale"].flatMap(s=>st(t[s],0,s)));return(n.length>0?n:Ce(st(t))).join(`
|
|
27
|
+
`).filter(d=>d.trim())).map(d=>typeof d=="string"?d:JSON.stringify(d)).filter(d=>d.trim()),s=ja(r,e),o=s.filter(d=>d.category==="decision").map(d=>d.text),i=s.filter(d=>d.category==="rule").map(d=>d.text),a=s.filter(d=>d.category==="file").map(d=>d.text),c=s.filter(d=>d.category==="fix").map(d=>d.text),u=s.filter(d=>d.category==="blocker").map(d=>d.text),p=s.filter(d=>d.category==="next_action").map(d=>d.text),l=s.filter(d=>d.category==="deploy").map(d=>d.text);return{summary:Ca(r),decisions:o,projectRules:i,filesChanged:a,bugsFixed:c,commands:l,blockers:u,nextActions:p,durableFacts:s}}function J(t){let e=new Set,n=[];for(let r of t){let s=r?.replace(/\s+/g," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function Ia(t){let e=new Map;for(let n of t){if(!n||!n.id||!Number.isFinite(n.sequence))continue;let r=n.sourceEventId?`${n.agent}:${n.sourceEventId}`:n.id,s=e.get(r);(!s||n.sequence>s.sequence)&&e.set(r,n)}return[...e.values()].sort((n,r)=>n.sequence-r.sequence||n.timestamp.localeCompare(r.timestamp))}function Aa(t){let e=t.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_./:-]+/gu)??[],n=new Set;for(let r of e)if(!(r.length<2||/^\d+$/u.test(r))&&(n.add(r),n.size>=40))break;return[...n]}function Ma(t){let e=Jt(t);return{...t,knowledgeClass:e.knowledgeClass,importanceScore:e.score,retrievalTerms:Aa(t.content),tags:J([...t.tags,"level:fact",`class:${e.knowledgeClass}`,`kind:${t.kind}`])}}function Pa(t){return t.map(e=>{try{return JSON.stringify({type:e.type,role:e.role,data:e.data,provenance:{sourcePath:e.provenance.sourcePath,files:e.provenance.files}})}catch{return""}}).filter(Boolean)}function Ea(t,e,n){let r=tt(Pa(e),t.nativeSessionId),s=n.filter(u=>u.kind==="todo").map(u=>u.content),o=n.flatMap(u=>u.provenance.sourcePaths),i=n.filter(u=>u.kind==="architecture").map(u=>u.content),a=J([...s,...r.nextActions]),c=J([...r.nextActions,...s]);return{summary:r.summary,state:{task:c[0]??a[0],decisions:J(r.decisions),files:J([...r.filesChanged,...o]),todos:a,completed:J(r.bugsFixed),blockers:J(r.blockers),nextActions:c,architecture:J(i)}}}function nt(t,e){let n=Ia(e),r=ar(t,n).map(Ma),s=r.filter(p=>Jt(p).persist).sort((p,l)=>l.importanceScore-p.importanceScore),{summary:o,state:i}=Ea(t,n,s),a=s.map(p=>({fingerprint:p.fingerprint,kind:p.kind,knowledgeClass:p.knowledgeClass,importanceScore:p.importanceScore,content:p.content,terms:p.retrievalTerms})),c=lr(n,s),u=p=>r.filter(l=>l.knowledgeClass===p).length;return{version:2,normalizedEvents:n,summary:o,state:i,candidates:s,retrievalIndex:a,hierarchy:c,stats:{inputEvents:e.length,normalizedEvents:n.length,extractedCandidates:r.length,persistedCandidates:s.length,permanent:u("permanent"),task:u("task"),session:u("session"),transient:u("transient")}}}import{createHash as Oa}from"node:crypto";import{chmodSync as hr,existsSync as Ta,mkdirSync as Ra,readFileSync as Na,renameSync as _a,writeFileSync as Sr}from"node:fs";import{dirname as kr,join as rt}from"node:path";var Qt="toolnet.context-offload.v1",$a="toolnet.context-offload-asset.v1",Ka=256,Fa=new Set(["tool_call","tool_result","file_read","file_write","file_edit","command","test","artifact"]);function vr(t){return rt(t,".toolnet","offload")}function La(t){return rt(vr(t),"assets")}function wr(t){return rt(vr(t),"graph.json")}function br(t){Ra(t,{recursive:!0,mode:448});try{hr(t,448)}catch{}}function Wa(t,e){br(kr(t));let n=`${t}.${process.pid}.${Date.now()}.tmp`;Sr(n,e,{encoding:"utf8",mode:384}),_a(n,t);try{hr(t,384)}catch{}}function Xt(t){return Array.isArray(t)?t.map(Xt):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Xt(n)])):t}function Da(t){return Oa("sha256").update(JSON.stringify(Xt(t)),"utf8").digest("hex")}function Yt(){return{schema:Qt,version:1,updatedAt:new Date(0).toISOString(),nodes:[]}}function za(t){let e=wr(t);if(!Ta(e))return Yt();try{let n=JSON.parse(Na(e,"utf8"));return n.schema!==Qt||n.version!==1||!Array.isArray(n.nodes)?Yt():n}catch{return Yt()}}function qa(t,e){Wa(wr(t),JSON.stringify(e,null,2)+`
|
|
28
|
+
`)}function Va(t,e=260){if(typeof t!="string")return null;let n=t.replace(/\s+/gu," ").trim();return n?n.slice(0,e):null}function Ha(t){let e=[...t.provenance.files??[],t.provenance.sourcePath],n=[];for(let r of e){let s=Va(r);if(!(!s||n.includes(s))&&(n.push(s),n.length===3))break}return n}function Ba(t){return`${t.agent}:${t.sourceEventId??t.id}`.replace(/\s+/gu," ").trim().slice(0,120)}function Ja(t,e){br(kr(t));try{return Sr(t,e,{encoding:"utf8",flag:"wx",mode:384}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function Ga(t,e){let n=t.nodes.find(s=>s.id===e.id),r=n?{...n,kind:e.kind,bytes:e.bytes,sourceRefs:Array.from(new Set([...n.sourceRefs,...e.sourceRefs])).slice(-8),files:Array.from(new Set([...n.files,...e.files])).slice(0,6)}:e;return{schema:Qt,version:1,updatedAt:new Date().toISOString(),nodes:[...t.nodes.filter(s=>s.id!==e.id),r].slice(-Ka)}}function xr(t,e){let n=za(t),r=0,s=0,o=0,i=[];for(let a of e){if(!Fa.has(a.type))continue;r+=1;let c=Da({type:a.type,data:a.data}),u={schema:$a,version:1,assetId:c,event:{type:a.type,agent:a.agent,nativeSessionId:a.nativeSessionId,timestamp:a.timestamp,sourceEventId:a.sourceEventId,provenance:a.provenance,data:a.data}},p=JSON.stringify(u,null,2)+`
|
|
29
|
+
`;Ja(rt(La(t),`${c}.json`),p)?s+=1:o+=1,i.push(c),n=Ga(n,{id:c,kind:a.type,bytes:Buffer.byteLength(p,"utf8"),createdAt:a.timestamp,sourceRefs:[Ba(a)],files:Ha(a)})}return r>0&&qa(t,n),{eligible:r,written:s,deduped:o,graphNodes:n.nodes.length,assetIds:i}}import{createHash as nc}from"node:crypto";import{existsSync as rc,readdirSync as sc,readFileSync as oc}from"node:fs";import{basename as ic,join as Wr}from"node:path";import{randomUUID as Ir}from"node:crypto";var I=class extends Error{constructor(n,r){super(n);this.statusCode=r}statusCode};function xe(t){let e=new Set,n=[];for(let r of t){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function ee(t){let e=t.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,120);if(!e)throw new I("Invalid Wiki slug",400);return e}function jr(t){let e=[];for(let n of t.matchAll(/\[\[([^\[\]]+)\]\]/gu)){let r=n[1]?.trim();r&&e.push(ee(r))}return xe(e)}function Ua(t){return t.normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}_-]+/u).map(e=>e.trim()).filter(e=>e.length>=2)}function Cr(t){return{id:`revision-${Ir()}`,pageId:t.id,slug:t.slug,revision:t.revision,title:t.title,...t.summary?{summary:t.summary}:{},content:t.content,tags:[...t.tags],links:[...t.links],createdAt:t.updatedAt}}function Z(t){return structuredClone(t)}var st=class{constructor(e){this.store=e}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}async mutate(e){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=e(s),s.updatedAt=new Date().toISOString(),await this.store.save(s)});return this.queue=r.then(()=>{},()=>{}),await r,n}async summary(){let e=await this.ensureState(),n=new Set(e.pages.flatMap(r=>r.links));return{schema:"toolnet.wiki-summary.v1",projectId:e.projectId,pages:e.pages.length,revisions:e.revisions.length,tags:xe(e.pages.flatMap(r=>r.tags)).sort((r,s)=>r.localeCompare(s)),links:e.pages.reduce((r,s)=>r+s.links.length,0),orphanPages:e.pages.filter(r=>r.links.length===0&&!n.has(r.slug)).length,automatedPages:e.pages.filter(r=>r.tags.some(s=>s.startsWith("toolnet-auto-"))).length,updatedAt:e.updatedAt}}async listPages(){let e=await this.ensureState();return Z([...e.pages].sort((n,r)=>n.title.localeCompare(r.title)))}async getPage(e){let n=await this.ensureState(),r=ee(e),s=n.pages.find(o=>o.slug===r||o.id===e);if(!s)throw new I(`Wiki page not found: ${e}`,404);return Z(s)}async createPage(e){return this.mutate(n=>{let r=e.title.trim(),s=e.content.trim();if(!r)throw new I("Wiki title is required",400);let o=ee(e.slug??r);if(n.pages.some(c=>c.slug===o))throw new I(`Wiki page already exists: ${o}`,409);let i=new Date().toISOString(),a={id:`wiki-${Ir()}`,slug:o,title:r,...e.summary?.trim()?{summary:e.summary.trim()}:{},content:s,tags:xe(e.tags??[]),links:jr(s),revision:1,createdAt:i,updatedAt:i};return n.pages.push(a),n.revisions.push(Cr(a)),Z(a)})}async updatePage(e,n){return this.mutate(r=>{let s=ee(e),o=r.pages.find(i=>i.slug===s||i.id===e);if(!o)throw new I(`Wiki page not found: ${e}`,404);if(n.title!==void 0){let i=n.title.trim();if(!i)throw new I("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=jr(o.content)),n.tags!==void 0&&(o.tags=xe(n.tags)),o.revision+=1,o.updatedAt=new Date().toISOString(),r.revisions.push(Cr(o)),Z(o)})}async history(e){let n=await this.getPage(e),r=await this.ensureState();return Z(r.revisions.filter(s=>s.pageId===n.id).sort((s,o)=>o.revision-s.revision))}async backlinks(e){let n=await this.getPage(e),r=await this.ensureState();return Z(r.pages.filter(s=>s.links.includes(n.slug)).sort((s,o)=>s.title.localeCompare(o.title)))}async search(e,n=10){let r=await this.ensureState(),s=xe(Ua(e));if(s.length===0)return[];let o=Math.max(1,Math.min(20,Math.floor(n))),i=[];for(let a of r.pages){let c=a.title.toLowerCase(),u=a.slug.toLowerCase(),p=a.summary?.toLowerCase()??"",l=a.content.toLowerCase(),f=a.tags.map(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),f.some(S=>S===m)?d+=5:f.some(S=>S.includes(m))&&(d+=3),p.includes(m)&&(d+=2),l.includes(m)&&(d+=1);d>0&&i.push({page:Z(a),score:d})}return i.sort((a,c)=>c.score-a.score||c.page.updatedAt.localeCompare(a.page.updatedAt)).slice(0,o)}};var Ar="wiki/state.v1.json";function Ya(t){let e=new Date().toISOString();return{schema:"toolnet.wiki.v1",version:1,projectId:t.id,pages:[],revisions:[],createdAt:e,updatedAt:e}}function Xa(t,e){let n=JSON.parse(t);if(n.schema!=="toolnet.wiki.v1"||n.version!==1||n.projectId!==e.id||!Array.isArray(n.pages)||!Array.isArray(n.revisions))throw new Error("Invalid ToolNet Wiki state");return n}var ot=class{constructor(e,n){this.storage=e;this.project=n}storage;project;async load(){let e=await this.storage.getText(Ar);if(!e){let n=Ya(this.project);return await this.save(n),n}return Xa(e,this.project)}async save(e){await this.storage.put(Ar,JSON.stringify(e,null,2),"application/json")}};import{createHash as Qa,randomUUID as Mr}from"node:crypto";var Pr="wiki/governance.v1.json",Rr="toolnet.knowledge-governance.v1",Er=500,je={autoApproveThreshold:.86,criticalApproveThreshold:.94,staleAfterDays:90};function Za(t,e=0,n=1){return Math.max(e,Math.min(n,t))}function Zt(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function Or(t){return Qa("sha256").update(t.normalize("NFKC").replace(/\s+/gu," ").trim()).digest("hex")}function ec(t){let e=[t.title,t.summary??"",t.content.slice(0,2e3),...t.tags].join(" ").toLowerCase();return/\b(?:architecture|security|authentication|authorization|auth|database|production|deploy|deployment|payment|billing|permission|permissions|acl|credential|secret|migration)\b/u.test(e)}function tc(t){let e=t.sourceType==="skill"?.96:t.sourceType==="memory"?.94:.88,n=t.tags.map(r=>r.toLowerCase());return(n.includes("permanent")||n.includes("task"))&&(e+=.03),t.content.length>=200&&(e+=.02),t.content.length<80&&(e-=.05),t.title.length<4&&(e-=.05),Za(e)}function Tr(t){let e=new Date().toISOString();return{schema:Rr,version:1,projectId:t,policy:{...je},reviews:[],audit:[],createdAt:e,updatedAt:e}}function Nr(t){let e=t.autoApproveThreshold??je.autoApproveThreshold,n=t.criticalApproveThreshold??je.criticalApproveThreshold,r=t.staleAfterDays??je.staleAfterDays;if(!Number.isFinite(e)||e<.5||e>1)throw new I("Invalid autoApproveThreshold",400);if(!Number.isFinite(n)||n<.5||n>1)throw new I("Invalid criticalApproveThreshold",400);if(!Number.isInteger(r)||r<1||r>3650)throw new I("Invalid staleAfterDays",400);return{autoApproveThreshold:e,criticalApproveThreshold:n,staleAfterDays:r}}var it=class{constructor(e,n){this.storage=e;this.project=n}storage;project;async load(){let e=await this.storage.getText(Pr);if(!e){let n=Tr(this.project.id);return await this.save(n),n}try{let n=JSON.parse(e);if(n.schema!==Rr||n.version!==1||n.projectId!==this.project.id||!Array.isArray(n.reviews)||!Array.isArray(n.audit))throw new Error("invalid");return{...n,policy:Nr(n.policy??je)}}catch{let n=Tr(this.project.id);return await this.save(n),n}}async save(e){await this.storage.put(Pr,JSON.stringify(e,null,2),"application/json")}},at=class{constructor(e){this.store=e}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}audit(e,n,r,s={}){e.audit.push({id:Mr(),action:n,principal:r,...s.reviewId?{reviewId:s.reviewId}:{},...s.sourceKey?{sourceKey:s.sourceKey}:{},timestamp:new Date().toISOString(),...s.metadata?{metadata:s.metadata}:{}}),e.audit.length>Er&&(e.audit=e.audit.slice(-Er))}async mutate(e){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=await e(s),s.updatedAt=new Date().toISOString(),await this.store.save(s)});return this.queue=r.then(()=>{},()=>{}),await r,n}async policy(){return{...(await this.ensureState()).policy}}async setPolicy(e,n){return this.mutate(r=>(r.policy=Nr({...r.policy,...e}),this.audit(r,"policy:update",n,{metadata:{...r.policy}}),{...r.policy}))}async summary(){let e=await this.ensureState(),n=r=>e.reviews.filter(s=>s.status===r).length;return{schema:"toolnet.knowledge-governance-summary.v1",projectId:e.projectId,pending:n("pending"),approved:n("approved"),rejected:n("rejected"),superseded:n("superseded"),criticalPending:e.reviews.filter(r=>r.status==="pending"&&r.risk==="critical").length,conflictPending:e.reviews.filter(r=>r.status==="pending"&&r.risk==="conflict").length,auditEvents:e.audit.length,policy:{...e.policy},updatedAt:e.updatedAt}}async listReviews(e){let n=await this.ensureState();return structuredClone(n.reviews.filter(r=>!e||r.status===e).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt)))}async auditLog(e=100){let n=await this.ensureState(),r=Math.max(1,Math.min(500,Math.floor(e)));return structuredClone(n.audit.slice(-r).reverse())}async assess(e,n){let r=await this.ensureState(),s=tc(e),o=Zt(e.title),i=n.filter(p=>p.slug!==e.slug&&Zt(p.title)===o&&Or(p.content)!==Or(e.content)).map(p=>p.slug),a=ec(e),c=[];s<r.policy.autoApproveThreshold&&c.push(`confidence:${s.toFixed(2)}`),a&&s<r.policy.criticalApproveThreshold&&c.push("critical-knowledge"),i.length>0&&c.push("conflicting-knowledge");let u=i.length>0?"conflict":a?"critical":"normal";return{confidence:s,risk:u,requiresReview:i.length>0||s<r.policy.autoApproveThreshold||a&&s<r.policy.criticalApproveThreshold,reasons:c,conflicts:i}}async gate(e,n){let r=await this.assess(e,n);return this.mutate(s=>{let o=s.reviews.find(c=>c.sourceKey===e.sourceKey&&c.digest===e.digest);if(o?.status==="approved")return{allowed:!0,mode:"review-approved",assessment:r,review:structuredClone(o)};if(o?.status==="rejected")return{allowed:!1,mode:"rejected",assessment:r,review:structuredClone(o)};if(!r.requiresReview)return this.audit(s,"knowledge:auto-approved","system",{sourceKey:e.sourceKey,metadata:{confidence:r.confidence,risk:r.risk}}),{allowed:!0,mode:"auto-approved",assessment:r};if(o?.status==="pending")return{allowed:!1,mode:"pending-review",assessment:r,review:structuredClone(o)};let i=new Date().toISOString(),a={id:Mr(),sourceKey:e.sourceKey,sourceType:e.sourceType,slug:e.slug,marker:e.marker,digest:e.digest,title:e.title,...e.summary?{summary:e.summary}:{},content:e.content,tags:[...new Set([...e.tags,e.marker])],confidence:r.confidence,risk:r.risk,reasons:[...r.reasons],conflicts:[...r.conflicts],status:"pending",createdAt:i,updatedAt:i};return s.reviews.push(a),this.audit(s,"knowledge:review-requested","system",{reviewId:a.id,sourceKey:a.sourceKey,metadata:{confidence:a.confidence,risk:a.risk}}),{allowed:!1,mode:"pending-review",assessment:r,review:structuredClone(a)}})}async markApplied(e,n){await this.mutate(r=>{let s=r.reviews.find(o=>o.sourceKey===e&&o.digest===n&&o.status==="approved");s&&(s.appliedAt=new Date().toISOString(),s.updatedAt=s.appliedAt,this.audit(r,"knowledge:applied",s.reviewedBy??"system",{reviewId:s.id,sourceKey:e}))})}async decide(e,n,r){return this.mutate(async s=>{let o=s.reviews.find(u=>u.id===e);if(!o)throw new I(`Governance review not found: ${e}`,404);if(o.status!=="pending")throw new I("Governance review is already resolved",409);let i=new Date().toISOString();if(o.reviewedAt=i,o.reviewedBy=n.principal,o.updatedAt=i,n.note?.trim()&&(o.reviewNote=n.note.trim()),n.action==="reject")return o.status="rejected",this.audit(s,"knowledge:rejected",n.principal,{reviewId:e,sourceKey:o.sourceKey}),structuredClone(o);if(n.action==="supersede")return o.status="superseded",n.targetReviewId&&(o.supersededBy=n.targetReviewId),this.audit(s,"knowledge:superseded",n.principal,{reviewId:e,sourceKey:o.sourceKey,metadata:{targetReviewId:n.targetReviewId}}),structuredClone(o);if(n.action==="merge"){if(!n.targetReviewId)throw new I("targetReviewId is required for merge",400);let u=s.reviews.find(p=>p.id===n.targetReviewId);if(!u)throw new I("Merge target review not found",404);return o.status="superseded",o.mergedInto=u.id,this.audit(s,"knowledge:merged",n.principal,{reviewId:e,sourceKey:o.sourceKey,metadata:{targetReviewId:u.id}}),structuredClone(o)}o.status="approved";let c=(await r.listPages()).find(u=>u.slug===o.slug);if(c&&!c.tags.includes(o.marker))throw new I(`Wiki page '${o.slug}' is manually managed`,409);return c?await r.updatePage(o.slug,{title:o.title,summary:o.summary??"",content:o.content,tags:o.tags}):await r.createPage({slug:o.slug,title:o.title,...o.summary?{summary:o.summary}:{},content:o.content,tags:o.tags}),o.appliedAt=i,this.audit(s,"knowledge:approved",n.principal,{reviewId:e,sourceKey:o.sourceKey}),structuredClone(o)})}async quality(e){let n=await this.ensureState(),r=await e.listPages(),s=Date.now(),o=n.policy.staleAfterDays*864e5,i=r.map(p=>{let l=s-Date.parse(p.updatedAt);return{slug:p.slug,title:p.title,updatedAt:p.updatedAt,ageDays:Math.max(0,Math.floor(l/864e5)),stale:Number.isFinite(l)&&l>o}}).filter(p=>p.stale).map(({stale:p,...l})=>l),a=new Map;for(let p of r){let l=Zt(p.title),f=a.get(l)??[];f.push(p),a.set(l,f)}let c=[...a.entries()].filter(([,p])=>p.length>1).map(([p,l])=>({title:p,pages:l.map(f=>f.slug)})),u=n.reviews.filter(p=>p.status==="pending");return{schema:"toolnet.knowledge-quality.v1",totalPages:r.length,automatedPages:r.filter(p=>p.tags.some(l=>l.startsWith("toolnet-auto-"))).length,manualPages:r.filter(p=>!p.tags.some(l=>l.startsWith("toolnet-auto-"))).length,stalePages:i,duplicateTitles:c,pendingReviews:u.length,lowConfidenceReviews:u.filter(p=>p.confidence<n.policy.autoApproveThreshold).length,conflicts:u.filter(p=>p.risk==="conflict").length,generatedAt:new Date().toISOString()}}};var Dr="wiki/automation.v1.json",zr="toolnet.wiki-automation.v1",nn=8e3,_r=new Set(["raw","rawtext","raw_text","rawtranscript","raw_transcript","transcript","messages","message","payload","prompt","response","assistantmessage","assistant_message","userprompt","user_prompt"]);function Ie(t){return nc("sha256").update(JSON.stringify(t)).digest("hex")}function Ce(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function $r(t){return Array.isArray(t)?t:[]}function qr(t){return typeof t!="string"?void 0:t.replace(/\s+/gu," ").trim()||void 0}function en(t){return Array.isArray(t)?t.map(qr).filter(e=>!!e):[]}function K(t,e){for(let n of e){let r=qr(t[n]);if(r)return r}}function Ae(t){let e=new Set,n=[];for(let r of t){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function ct(t,e=0,n=""){if(e>3)return[];let r=n.replace(/[^a-z0-9]/giu,"").toLowerCase();if(_r.has(r))return[];if(typeof t=="string"){let i=t.replace(/\s+/gu," ").trim();return i.length<8?[]:[i]}if(Array.isArray(t))return t.flatMap(i=>ct(i,e+1,n));let s=Ce(t);if(!s)return[];let o=[];for(let[i,a]of Object.entries(s)){let c=i.replace(/[^a-z0-9]/giu,"").toLowerCase();_r.has(c)||o.push(...ct(a,e+1,i))}return o}function Kr(t){let n=Ae(["content","summary","text","value","statement","description","decision","task","knowledge","context","outcome","reason","rationale"].flatMap(s=>ct(t[s],0,s)));return(n.length>0?n:Ae(ct(t))).join(`
|
|
30
30
|
|
|
31
|
-
`).slice(0,
|
|
31
|
+
`).slice(0,nn)}function Fr(t,e){return K(t,["id","key","fingerprint","knowledgeId","sceneId"])??e}function Lr(t,e){return K(t,["title","name","topic","label","task","kind","type"])??e}function ac(t){return(K(t,["knowledgeClass","class","classification","scope"])??"").toLowerCase()}function cc(t){return(K(t,["kind","sceneKind","type"])??"").toLowerCase()}function uc(t){let e=Ce(t);if(!e)return[];let n=[],r=$r(e.knowledge);for(let[o,i]of r.entries()){let a=Ce(i);if(!a)continue;let c=ac(a);if(c==="session"||c==="transient")continue;let u=Kr(a);if(u.length<20)continue;let p=Fr(a,Ie(a).slice(0,16)),l=Lr(a,`Durable Memory ${o+1}`);n.push({sourceKey:`memory:${p}`,sourceType:"memory",title:l,summary:K(a,["summary","description"]),content:u,tags:Ae(["toolnet","auto","memory",...c?[c]:[]])})}let s=$r(e.scenes);for(let[o,i]of s.entries()){let a=Ce(i);if(!a)continue;let c=cc(a);if(c==="session-context")continue;let u=Kr(a);if(u.length<20)continue;let p=Fr(a,Ie(a).slice(0,16)),l=Lr(a,`Knowledge Scene ${o+1}`);n.push({sourceKey:`scene:${p}`,sourceType:"scene",title:l,summary:K(a,["summary","description"]),content:u,tags:Ae(["toolnet","auto","scene",...c?[c]:[]])})}return n}function lc(t){return Wr(t,".toolnet","memory","skills")}function dc(t){let e=lc(t);if(!rc(e))return{candidates:[],failed:0};let n=[],r=0,s=sc(e).filter(o=>o.endsWith(".json")).sort();for(let o of s)try{let i=JSON.parse(oc(Wr(e,o),"utf8")),a=Ce(i);if(!a||a.schema!=="toolnet.skill-memory.v1")continue;let c=K(a,["id","fingerprint"])??ic(o,".json"),u=K(a,["task"])??"",p=K(a,["title"])||u||`Reusable Skill ${c.slice(0,8)}`,l=K(a,["summary"])??void 0,f=en(a.steps),d=en(a.verification),m=en(a.files),S=[];u&&S.push(`## Task
|
|
32
32
|
${u}`),l&&S.push(`## Summary
|
|
33
33
|
${l}`),f.length>0&&S.push(`## Procedure
|
|
34
|
-
${f.map((
|
|
34
|
+
${f.map((y,v)=>`${v+1}. ${y}`).join(`
|
|
35
35
|
`)}`),d.length>0&&S.push(`## Verification
|
|
36
|
-
${d.map(
|
|
37
|
-
`)}`),
|
|
38
|
-
${
|
|
39
|
-
`)}`);let
|
|
40
|
-
|
|
41
|
-
`).slice(0,
|
|
42
|
-
`).slice(0,
|
|
43
|
-
`,{encoding:"utf8",mode:384}),
|
|
44
|
-
`,c=
|
|
45
|
-
`,"application/json"),u}};function
|
|
36
|
+
${d.map(y=>`- ${y}`).join(`
|
|
37
|
+
`)}`),m.length>0&&S.push(`## Relevant Files
|
|
38
|
+
${m.map(y=>`- \`${y}\``).join(`
|
|
39
|
+
`)}`);let g=S.join(`
|
|
40
|
+
|
|
41
|
+
`).slice(0,nn);if(g.length<20)continue;n.push({sourceKey:`skill:${c}`,sourceType:"skill",title:p,summary:l,content:g,tags:["toolnet","auto","skill","sop"]})}catch{r+=1}return{candidates:n,failed:r}}function tn(t){let e=new Date().toISOString();return{schema:zr,version:1,projectId:t,entries:[],createdAt:e,updatedAt:e}}async function pc(t,e){let n=await t.getText(Dr);if(!n)return tn(e);try{let r=JSON.parse(n);return r.schema!==zr||r.version!==1||r.projectId!==e||!Array.isArray(r.entries)?tn(e):r}catch{return tn(e)}}async function fc(t,e){await t.put(Dr,JSON.stringify(e,null,2),"application/json")}function mc(t){return`toolnet-auto-${Ie(t).slice(0,12)}`}function gc(t){let e=ee(t.title).slice(0,72),n=Ie(t.sourceKey).slice(0,10);return ee(`auto-${t.sourceType}-${e}-${n}`)}function yc(t){return[`> Auto-generated by ToolNet Knowledge Automation from ${t.sourceType==="skill"?"reusable Skill Memory":t.sourceType==="scene"?"semantic memory scene":"durable memory"}.`,"",t.content].join(`
|
|
42
|
+
`).slice(0,nn)}function hc(t){return Ie({sourceType:t.sourceType,title:t.title,summary:t.summary,content:t.content,tags:t.tags})}function Sc(t,e){return t.tags.includes(e)}async function Vr(t){let e=uc(t.hierarchy),n=dc(t.project.rootPath),r=new Map;for(let d of[...e,...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:e.length+n.candidates.length,eligible:s.length,created:0,updated:0,unchanged:0,skipped:0,failed:n.failed,reviewPending:0,autoApproved:0,reviewApproved:0,pages:[]},i=new st(new ot(t.storage,t.project));await i.initialize();let a=new at(new it(t.storage,t.project));await a.initialize();let c=await pc(t.storage,t.project.id),u=await i.listPages(),p=new Map(u.map(d=>[d.slug,d])),l=new Map(c.entries.map(d=>[d.sourceKey,d]));for(let d of s)try{let m=mc(d.sourceKey),S=hc(d),g=l.get(d.sourceKey),y=g?.slug??gc(d),v=p.get(y);if(v&&!Sc(v,m)){o.skipped+=1;continue}let x=Ae([...d.tags,m]),O=yc(d),P=await a.gate({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:y,marker:m,digest:S,title:d.title,...d.summary?{summary:d.summary}:{},content:O,tags:x},[...p.values()]);if(!P.allowed){P.mode==="pending-review"?o.reviewPending+=1:o.skipped+=1;continue}P.mode==="auto-approved"?o.autoApproved+=1:P.mode==="review-approved"&&(o.reviewApproved+=1),v?g?.digest!==S?(v=await i.updatePage(y,{title:d.title,summary:d.summary??"",content:O,tags:x}),p.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:y,action:"unchanged"})):(v=await i.createPage({slug:y,title:d.title,summary:d.summary,content:O,tags:x}),p.set(v.slug,v),o.created+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:v.slug,action:"created"}));let T=new Date().toISOString(),j={sourceKey:d.sourceKey,sourceType:d.sourceType,slug:y,digest:S,marker:m,updatedAt:T},b=c.entries.findIndex(D=>D.sourceKey===d.sourceKey);b>=0?c.entries[b]=j:c.entries.push(j),l.set(d.sourceKey,j),await a.markApplied(d.sourceKey,S)}catch(m){if(m instanceof I&&m.statusCode===409){o.skipped+=1;continue}o.failed+=1}let f=new Date().toISOString();return c.updatedAt=f,c.lastRunAt=f,c.entries.sort((d,m)=>d.sourceKey.localeCompare(m.sourceKey)),await fc(t.storage,c),o}import{createHash as kc}from"node:crypto";import{chmodSync as Br,existsSync as vc,mkdirSync as wc,readFileSync as rg,readdirSync as sg,renameSync as bc,statSync as og,writeFileSync as xc}from"node:fs";import{join as Jr}from"node:path";var jc="toolnet.skill-memory.v1",Hr=5,Cc=16,Ic=24,Ac=32;function Mc(t){return kc("sha256").update(t).digest("hex")}function Pe(t,e=Number.MAX_SAFE_INTEGER){let n=new Set,r=[];for(let s of t){let o=s.replace(/\s+/gu," ").trim();if(!o)continue;let i=o.normalize("NFKC").toLowerCase();if(!n.has(i)&&(n.add(i),r.push(o),r.length>=e))break}return r}function rn(t,e=360){let n=t.replace(/\s+/gu," ").trim();return n.length<=e?n:n.slice(0,Math.max(0,e-1)).trimEnd()+"\u2026"}function Pc(t){return t.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu,"Bearer [REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/gu,"[REDACTED]").replace(/\b(api[_-]?key|token|password|passwd|secret)\b(\s*[:=]\s*)(["']?)[^\s"'`]+/giu,"$1$2[REDACTED]")}function q(t,e=360){return t&&rn(Pc(t),e)||void 0}function Ee(t,e){for(let n of e){let r=t[n];if(typeof r=="string"&&r.trim())return r}}function Gr(t,e){for(let n of e){let r=t[n];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()&&Number.isFinite(Number(r)))return Number(r)}}function Ur(t,e){for(let n of e){let r=t[n];if(typeof r=="boolean")return r;if(typeof r=="string"){let s=r.trim().toLowerCase();if(["true","yes","pass","passed","success","succeeded","ok"].includes(s))return!0;if(["false","no","fail","failed","error"].includes(s))return!1}}}function Yr(t){let e=t.data??{};if(Ur(e,["passed","pass","success","succeeded","ok"])===!1)return!0;let r=Gr(e,["exitCode","exit_code","code","statusCode"]);if(r!==void 0&&r!==0)return!0;let s=Ee(e,["status","result","outcome"]);return!!(s&&/\b(fail(?:ed)?|error|broken|cancelled)\b/iu.test(s))}function Me(t){let e=t.data??{};if(Yr(t))return!1;if(Ur(e,["passed","pass","success","succeeded","ok"])===!0||Gr(e,["exitCode","exit_code","code","statusCode"])===0)return!0;let s=Ee(e,["status","result","outcome"]);return s&&/\b(pass(?:ed)?|success(?:ful)?|succeeded|ok|green|complete(?:d)?)\b/iu.test(s)?!0:t.type==="commit"||t.type==="deploy"}function Xr(t){let e=t.data??{},n=Ee(e,["path","file","filePath","filename","target"]);if(n)return q(n,260);let r=t.provenance?.files;return q(r?.[0],260)}function sn(t){return q(Ee(t.data??{},["command","cmd","script"]),420)}function ce(t){return q(Ee(t.data??{},["name","test","suite","title","message","text","result","status"]),300)}function Ec(t){let e=[];for(let n of[...t].sort((r,s)=>r.sequence-s.sequence))if(Me(n)){if(n.type==="test"){let r=ce(n)??sn(n)??"Tests passed";e.push(`Test passed: ${r}`);continue}if(n.type==="commit"){let r=ce(n);e.push(r?`Commit: ${r}`:"Commit completed");continue}if(n.type==="deploy"){let r=ce(n);e.push(r?`Deploy: ${r}`:"Deployment completed")}}return Pe(e,10)}function Oc(t,e){let n=[];for(let r of[...t].sort((s,o)=>s.sequence-o.sequence))switch(r.type){case"file_write":case"file_edit":{let s=Xr(r);s&&n.push(`Update ${s}`);break}case"command":{if(Yr(r))break;let s=sn(r);s&&n.push(`Run: ${s}`);break}case"test":{if(!Me(r))break;let s=ce(r)??sn(r)??"project tests";n.push(`Verify: ${s}`);break}case"commit":{if(!Me(r))break;let s=ce(r);n.push(s?`Commit: ${s}`:"Commit verified changes");break}case"deploy":{if(!Me(r))break;let s=ce(r);n.push(s?`Deploy: ${s}`:"Deploy verified build");break}default:break}if(n.length===0)for(let r of e.files.slice(0,8)){let s=q(r,260);s&&n.push(`Update ${s}`)}return Pe(n,Cc)}function Tc(t,e){let n=[...e.files];for(let r of t){let s=Xr(r);s&&n.push(s);for(let o of r.provenance?.files??[]){let i=q(o,260);i&&n.push(i)}}return Pe(n,Ic)}function Rc(t){return Pe(t.filter(e=>["file_write","file_edit","command","test","commit","deploy"].includes(e.type)).map(e=>e.id),Ac)}function Nc(t){return t.map(n=>n.timestamp).filter(Boolean).sort().at(-1)??new Date(0).toISOString()}function Qr(t,e,n){if(e.length===0)return[];let r=Ec(e),s=Pe(n.completed.map(m=>q(m,280)??""),Hr);if(!(s.length>0||e.some(m=>["test","commit","deploy"].includes(m.type)&&Me(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=Oc(e,n);if(c.length===0)return[];let u=Tc(e,n),p=Rc(e),l=Math.min(...e.map(m=>m.sequence)),f=Math.max(...e.map(m=>m.sequence)),d=Nc(e);return a.slice(0,Hr).map(m=>{let S=[`Reusable procedure learned from successful task: ${m}.`,u.length>0?`Files: ${u.slice(0,6).join(", ")}.`:"",r.length>0?`Verification: ${r.slice(0,4).join("; ")}.`:""].filter(Boolean),g=JSON.stringify({projectId:t.projectId,task:m,steps:c,verification:r,files:u}),y=Mc(g);return{schema:jc,version:1,id:`skill-${y.slice(0,24)}`,fingerprint:y,projectId:t.projectId,title:rn(`SOP: ${m}`,180),task:m,summary:rn(S.join(" "),900),steps:c,verification:r,files:u,source:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,firstSequence:l,lastSequence:f,eventIds:p},createdAt:d}})}function _c(t){return Jr(t.rootPath,".toolnet","memory","skills")}function $c(t){let e=_c(t);return wc(e,{recursive:!0,mode:448}),Br(e,448),e}function Zr(t,e){if(e.length===0)return{written:0,deduped:0,files:[]};let n=$c(t),r=0,s=0,o=[];for(let i of e){if(i.projectId!==t.id)throw new Error(`Skill project mismatch: ${i.projectId} != ${t.id}`);let a=Jr(n,`${i.id}.json`);if(o.push(a),vc(a)){s+=1;continue}let c=`${a}.${process.pid}.${Date.now()}.tmp`;xc(c,JSON.stringify(i,null,2)+`
|
|
43
|
+
`,{encoding:"utf8",mode:384}),bc(c,a),Br(a,384),r+=1}return{written:r,deduped:s,files:o}}function es(t){return String(t).padStart(12,"0")}function Kc(t){return`projects/${t.projectId}/memory/learned`}var ut=class{constructor(e){this.storage=e}storage;async write(e,n,r){if(r.length===0||n.length===0)return null;let s=Math.min(...n.map(l=>l.sequence)),o=Math.max(...n.map(l=>l.sequence)),i={version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,createdAt:new Date().toISOString(),firstSequence:s,lastSequence:o,candidateCount:r.length,candidates:r},a=JSON.stringify(i,null,2)+`
|
|
44
|
+
`,c=w(r.map(l=>l.fingerprint).sort().join("|")).slice(0,16),u=w(e.sessionKey).slice(0,12),p=[Kc(e),"batches",`${es(s)}-${es(o)}-${u}-${c}.json`].join("/");return await this.storage.exists(p)||await this.storage.put(p,a,"application/json"),p}};import{createHash as Fc}from"node:crypto";function ts(t){return String(t).padStart(12,"0")}function ns(t){return Fc("sha256").update(t).digest("hex")}function Lc(t){return`projects/${t.projectId}/memory/hierarchy`}var lt=class{constructor(e){this.storage=e}storage;async write(e,n,r){if(n.length===0||r.facts.length===0)return null;let s=Math.min(...n.map(p=>p.sequence)),o=Math.max(...n.map(p=>p.sequence)),i={schema:"toolnet.memory-hierarchy-batch.v1",version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,createdAt:new Date().toISOString(),firstSequence:s,lastSequence:o,hierarchy:r},a=ns([...r.facts.map(p=>p.id),...r.knowledge.map(p=>p.id)].sort().join("|")).slice(0,16),c=ns(e.sessionKey).slice(0,12),u=[Lc(e),"batches",`${ts(s)}-${ts(o)}-${c}-${a}.json`].join("/");return await this.storage.exists(u)||await this.storage.put(u,`${JSON.stringify(i,null,2)}
|
|
45
|
+
`,"application/json"),u}};function Hc(t,e){if(!Dc(t))return{events:[],nextOffset:e};let n=Vc(t).size,r=Number.isFinite(e)?Math.max(0,e):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=n-r,o=Buffer.alloc(s),i=zc(t,"r");try{qc(i,o,0,s,r)}finally{Wc(i)}let a=o.toString("utf8"),c=a.lastIndexOf(`
|
|
46
46
|
`);if(c<0)return{events:[],nextOffset:r};let u=a.slice(0,c+1);return{events:u.split(`
|
|
47
|
-
`).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var
|
|
48
|
-
`))))}function
|
|
49
|
-
`).toLowerCase();return/\b(error|failed|failure|failing)\b/u.test(n)&&!/\b0\s+failed\b/u.test(n)?"failed":/\b(success|successful|completed|passed|green)\b/u.test(n)||/\b\d+\s+passed\b/u.test(n)?"passed":/\b(running|started|in[_ -]?progress)\b/u.test(n)?"running":"unknown"}function
|
|
50
|
-
`,a=
|
|
51
|
-
`)).slice(0,24),c=
|
|
52
|
-
`,"application/json"),
|
|
47
|
+
`).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var dt=class{constructor(e){this.options=e;this.journal=new ut(e.storage),this.hierarchyJournal=new lt(e.storage)}options;journal;hierarchyJournal;async learnNew(){let e=this.options.wal.loadState(),n=Number(e.sourceCursors["memory.learner.offset"]??0),r=Number.isFinite(n)?n:0,s=Hc(this.options.wal.eventsFile,r);if(s.events.length===0)return{scannedEvents:0,candidates:0,journalWritten:!1,nextOffset:s.nextOffset};let o=nt(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=Qr(this.options.identity,s.events,o.state),p=Zr(this.options.project,u);this.options.wal.setSourceCursor("memory.pipeline.version",2),this.options.wal.setSourceCursor("memory.pipeline.normalized_events",o.stats.normalizedEvents),this.options.wal.setSourceCursor("memory.pipeline.persisted",o.stats.persistedCandidates),this.options.wal.setSourceCursor("memory.pipeline.permanent",o.stats.permanent),this.options.wal.setSourceCursor("memory.pipeline.task",o.stats.task),this.options.wal.setSourceCursor("memory.pipeline.session",o.stats.session),this.options.wal.setSourceCursor("memory.pipeline.transient",o.stats.transient),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.version",o.hierarchy.version),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.raw",o.hierarchy.stats.raw),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.facts",o.hierarchy.stats.facts),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.scenes",o.hierarchy.stats.scenes),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.knowledge",o.hierarchy.stats.knowledge),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.journal_written",c?1:0),this.options.wal.setSourceCursor("memory.skill.assets",u.length),this.options.wal.setSourceCursor("memory.skill.written",p.written),this.options.wal.setSourceCursor("memory.skill.deduped",p.deduped);try{let l=xr(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 Vr({project:this.options.project,storage:this.options.storage,hierarchy:o.hierarchy});this.options.wal.setSourceCursor("memory.wiki_automation.scanned",l.scanned),this.options.wal.setSourceCursor("memory.wiki_automation.eligible",l.eligible),this.options.wal.setSourceCursor("memory.wiki_automation.created",l.created),this.options.wal.setSourceCursor("memory.wiki_automation.updated",l.updated),this.options.wal.setSourceCursor("memory.wiki_automation.unchanged",l.unchanged),this.options.wal.setSourceCursor("memory.wiki_automation.skipped",l.skipped),this.options.wal.setSourceCursor("memory.wiki_automation.failed",l.failed),this.options.wal.setSourceCursor("memory.wiki_automation.review_pending",l.reviewPending),this.options.wal.setSourceCursor("memory.wiki_automation.auto_approved",l.autoApproved),this.options.wal.setSourceCursor("memory.wiki_automation.review_approved",l.reviewApproved)}catch{this.options.wal.setSourceCursor("memory.wiki_automation.failed",1)}return this.options.wal.setSourceCursor("memory.learner.offset",s.nextOffset),{scannedEvents:s.events.length,candidates:i.length,journalWritten:a,nextOffset:s.nextOffset}}};import{closeSync as cu,existsSync as uu,openSync as lu,readSync as du,statSync as pu}from"node:fs";function rs(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Te(t){return t.toLowerCase().replace(/[^a-z0-9]/gu,"")}function Oe(t,e,n=0){if(n>8)return;if(Array.isArray(t)){for(let s of t.slice(0,50))Oe(s,e,n+1);return}let r=rs(t);if(r)for(let[s,o]of Object.entries(r))e(s,o,r),Oe(o,e,n+1)}function ue(t,e){let n=[];return Oe(t,(r,s)=>{e.has(Te(r))&&typeof s=="string"&&s.trim()&&n.push(s.trim())}),n}function Bc(t){let e=t.trim();if(!e.startsWith("{"))return null;try{return rs(JSON.parse(e))}catch{return null}}function Jc(t){let e=t.data;for(let r of["tool","toolName","tool_name"]){let s=e[r];if(typeof s=="string"&&s.trim())return s.trim().toLowerCase()}let n="";return Oe(e,(r,s,o)=>{if(n)return;let i=Te(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 Gc(t){let e=ue(t.data,new Set(["command","cmd","script"])),n=ue(t.data,new Set(["arguments","args"]));for(let r of n){let s=Bc(r);if(s)for(let o of ue(s,new Set(["command","cmd","script"])))e.push(o)}return Array.from(new Set(e.map(r=>r.trim()).filter(Boolean)))}function Uc(t){let e=ue(t.data,new Set(["filepath","file_path","filename","file","path","target"].map(Te)));return Array.from(new Set(e.map(n=>n.trim()).filter(n=>n.length>0&&n.length<1e3&&!n.includes(`
|
|
48
|
+
`))))}function Yc(t,e){return t.type==="file_edit"||t.type==="file_write"?"modified":/\b(delete|remove|unlink)\b/iu.test(e)?"deleted":/\b(create|add[_-]?file|new[_-]?file)\b/iu.test(e)?"created":/\b(edit|write|patch|apply[_-]?patch|replace|update[_-]?file)\b/iu.test(e)?"modified":null}function Xc(t){let e=ue(t.data,new Set(["patch","diff","arguments","input"].map(Te))),n=[];for(let r of e){let s=[{regex:/^\*\*\* Update File:\s*(.+)$/gimu,action:"modified"},{regex:/^\*\*\* Add File:\s*(.+)$/gimu,action:"created"},{regex:/^\*\*\* Delete File:\s*(.+)$/gimu,action:"deleted"}];for(let o of s)for(let i of r.matchAll(o.regex)){let a=i[1]?.trim();a&&n.push({kind:"file",text:a,fileAction:o.action,confidence:.99})}}return n}function Qc(t){let e=t.toLowerCase();return/\b(typecheck|type-check)\b/u.test(e)||/\btsc\b[\s\S]*--noemit\b/u.test(e)?"typecheck":/\b(eslint|lint)\b/u.test(e)?"lint":/\b(vitest|jest|pytest)\b/u.test(e)||/\bgo\s+test\b/u.test(e)||/\bcargo\s+test\b/u.test(e)||/\b(npm|pnpm|yarn)\s+(run\s+)?test\b/u.test(e)?"test":/\b(npm|pnpm|yarn)\s+(run\s+)?build\b/u.test(e)||/\bcargo\s+build\b/u.test(e)||/\bgo\s+build\b/u.test(e)||/\btsc\b/u.test(e)?"build":null}function Zc(t){let e=null;return Oe(t,(n,r)=>{if(e===null&&["exitcode","code"].includes(Te(n))){if(typeof r=="number"&&Number.isFinite(r)){e=r;return}if(typeof r=="string"){let s=Number(r);Number.isFinite(s)&&(e=s)}}}),e}function eu(t){return ue(t,new Set(["status","state","result","output","outputsummary","message","text"]))}function tu(t){let e=Zc(t.data);if(e!==null)return e===0?"passed":"failed";let n=eu(t.data).join(`
|
|
49
|
+
`).toLowerCase();return/\b(error|failed|failure|failing)\b/u.test(n)&&!/\b0\s+failed\b/u.test(n)?"failed":/\b(success|successful|completed|passed|green)\b/u.test(n)||/\b\d+\s+passed\b/u.test(n)?"passed":/\b(running|started|in[_ -]?progress)\b/u.test(n)?"running":"unknown"}function nu(t){let e=[],n=new Set;for(let r of t){let s=[r.kind,r.fileAction??"",r.checkKind??"",r.checkStatus??"",r.text].join("|");n.has(s)||(n.add(s),e.push(r))}return e}function ss(t){let e=[],n=Jc(t),r=Yc(t,n);if(r)for(let s of Uc(t))e.push({kind:"file",text:s,fileAction:r,confidence:t.type==="file_edit"||t.type==="file_write"?1:.96});e.push(...Xc(t));for(let s of Gc(t)){e.push({kind:"command",text:s,confidence:.98});let o=Qc(s);o&&e.push({kind:"test",text:s,checkKind:o,checkStatus:tu(t),confidence:.98})}return nu(e)}var ru=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function ne(t){return t.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function is(t){return ne(t).toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function te(t,e,n=0){if(!(n>6)){if(typeof t=="string"){e.push(t);return}if(Array.isArray(t)){for(let r of t.slice(0,50))te(r,e,n+1);return}if(!(!t||typeof t!="object"))for(let[r,s]of Object.entries(t))(ru.has(r)||["data","payload","parts","messages"].includes(r))&&te(s,e,n+1)}}function pt(t){return/\b(cancelled|canceled)\b|đã hủy|bỏ qua/iu.test(t)?"cancelled":/\b(blocked|blocker)\b|đang vướng|bị vướng|đang kẹt|chưa thể/iu.test(t)?"blocked":/\b(completed|complete|done|finished|passed)\b|hoàn thành|hoàn tất|đã xong|đã làm xong|\bxong\b/iu.test(t)?"completed":/\bin[\s_-]*progress\b|working on|đang làm|đang thực hiện|đang xử lý|đang triển khai/iu.test(t)?"in_progress":"pending"}function os(t){let e=ne(t);return/^(?:đang\s+làm|đang\s+thực\s+hiện|đang\s+xử\s+lý|đang\s+triển\s+khai|hoàn\s+thành|hoàn\s+tất|đã\s+xong|đã\s+làm\s+xong|xong|pending|in[\s_-]*progress|completed|complete|done|finished|blocked|cancelled|canceled)[.!]*$/iu.test(e)}function A(t,e,n,r,s={}){let o=ne(r),i=s.key??is(o);return{version:1,id:w([t.projectId,n,i,e.id,o,s.status??"",s.fileAction??"",s.checkKind??"",s.checkStatus??"",s.order??""].join("|")).slice(0,32),projectId:t.projectId,kind:n,key:i,text:o,status:s.status,fileAction:s.fileAction,checkKind:s.checkKind,checkStatus:s.checkStatus,order:s.order,confidence:s.confidence??.85,occurredAt:e.timestamp,sequence:e.sequence,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,eventId:e.id,sourceEventId:e.sourceEventId}}function su(t,e,n){let r=ne(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(t,e,"goal",i[1],{confidence:.97}));let a=r.match(/^(?:kế hoạch|plan)\s*(?::|-)\s*(.+)$/iu);a?.[1]&&s.push(A(t,e,"plan",a[1],{confidence:.95}));let c=/\b(?:phase|giai đoạn|giai doan|stage)\s*(\d+)\s*(?:[:\-–—]\s*)?([^.;\n]{0,220})/giu,u;for(;!o&&(u=c.exec(r));){let f=Number(u[1]),d=ne(u[2]??""),m=d&&!os(d)?`Phase ${f} - ${d}`:`Phase ${f}`;s.push(A(t,e,"phase",m,{key:`phase:${f}`,order:f,status:pt(r),confidence:.93}))}let p=n.match(/^\s*[-*]\s*\[([ xX])\]\s*(.+)$/u);p?.[2]&&s.push(A(t,e,"task",p[2],{status:p[1].trim()?"completed":pt(p[2]),confidence:.96}));let l=r.match(/^(?:todo|task|việc)\s*(\d+)?(?:\s*[:.\-–—]\s*|\s+)(.+)$/iu);if(l?.[2]){let f=l[1]?Number(l[1]):void 0,d=ne(l[2]),m=os(d);s.push(A(t,e,"task",m&&f!==void 0?`TODO ${f}`:d,{key:f!==void 0?`task:${f}`:is(d),order:f,status:pt(r),confidence:.93}))}if(/^(?:next|next action|next step|tiếp theo|bước tiếp theo|cần làm tiếp)\b/iu.test(r)){let f=r.replace(/^(?:next|next action|next step|tiếp theo|bước tiếp theo|cần làm tiếp)\s*(?::|-)?\s*/iu,"");f&&s.push(A(t,e,"next_action",f,{confidence:.9}))}return/\b(blocker|blocked)\b|đang vướng|bị vướng|đang kẹt/iu.test(r)&&s.push(A(t,e,"blocker",r,{confidence:.9})),/\b(chú ý|lưu ý|warning|attention|cẩn thận)\b/iu.test(r)&&s.push(A(t,e,"warning",r,{confidence:.88})),/\b(chốt|quyết định|decided|decision)\b/iu.test(r)&&s.push(A(t,e,"decision",r,{confidence:.9})),r.length<=300&&/^(?:đang\s+(?:sửa|cập nhật|triển khai|xử lý|làm|refactor|fix)|(?:i(?:'m| am)\s+)?(?:working on|implementing|fixing|refactoring|updating|editing)\b)/iu.test(r)&&s.push(A(t,e,"activity",r,{confidence:.86})),s}function le(t,e){if(e.length===0)return[];let n=[],r=new Set;function s(i){r.has(i.id)||(r.add(i.id),n.push(i))}for(let i of e){if(i.type==="user_prompt"||i.role==="user"){let c=[];te(i.data,c);let u=c.map(p=>ne(p)).find(p=>p.length>=8&&p.length<=1200&&!/^\[?toolnet\b/iu.test(p));u&&s(A(t,i,"request",u,{confidence:.96}))}for(let c of ss(i))s(A(t,i,c.kind,c.text,{fileAction:c.fileAction,checkKind:c.checkKind,checkStatus:c.checkStatus,status:c.kind==="test"?c.checkStatus==="passed"?"completed":c.checkStatus==="failed"?"blocked":c.checkStatus==="running"?"in_progress":"pending":void 0,confidence:c.confidence}));if(i.type==="decision"){let c=[];te(i.data,c);for(let u of c)s(A(t,i,"decision",u,{confidence:1}))}if(i.type==="todo"){let c=[];te(i.data,c);for(let u of c)s(A(t,i,"task",u,{status:pt(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(t,i,"file",u,{fileAction:"modified",confidence:1}))}if(i.type==="test"){let c=[];te(i.data,c);for(let u of c)s(A(t,i,"test",u,{confidence:1}))}let a=[];te(i.data,a);for(let c of a)for(let u of c.split(/\n+/u))for(let p of su(t,i,u))s(p)}let o=e[e.length-1];return s(A(t,o,"session",`${t.agent}:${t.nativeSessionId}`,{key:t.sessionKey,confidence:1})),n}function as(t){return String(t).padStart(12,"0")}var ft=class{constructor(e){this.storage=e}storage;async write(e,n){if(n.length===0)return null;let r=Math.min(...n.map(p=>p.sequence)),s=Math.max(...n.map(p=>p.sequence)),o={version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,createdAt:n.map(p=>p.occurredAt).sort().at(-1)??new Date().toISOString(),firstSequence:r,lastSequence:s,observations:n},i=JSON.stringify(o,null,2)+`
|
|
50
|
+
`,a=w(n.map(p=>JSON.stringify(p)).sort().join(`
|
|
51
|
+
`)).slice(0,24),c=w(e.sessionKey).slice(0,12),u=[`projects/${e.projectId}`,"work","observations",`${as(r)}-${as(s)}-${c}-${a}.json`].join("/");return await this.storage.put(u,i,"application/json"),u}};import{join as cs}from"node:path";import{mkdirSync as ou}from"node:fs";function ls(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function F(t,e=20){let n=[],r=new Set;for(let s of t.slice().reverse()){let o=ls(s);if(!(!o||r.has(o))&&(r.add(o),n.push(s),n.length>=e))break}return n.reverse()}function iu(t,e=20){let n=new Map;for(let r of t){let s=`${r.kind}|${ls(r.command)}`;n.delete(s),n.set(s,r)}return Array.from(n.values()).slice(-e)}function au(t){return t.kind==="phase"?/^Phase\s+\d+$/iu.test(t.text):t.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(t.text):!1}function us(t,e){let n=e.status??t?.status??"pending",r=n;t&&(t.status==="completed"&&n!=="completed"?r="completed":n==="pending"&&(t.status==="in_progress"||t.status==="blocked")&&(r=t.status));let s=t&&au(e)?t.title:e.text;return{id:t?.id??w(e.key).slice(0,24),title:s,status:r,order:e.order??t?.order,confidence:Math.max(e.confidence,t?.confidence??0),updatedAt:e.occurredAt,updatedBy:{agent:e.agent,nativeSessionId:e.nativeSessionId,eventId:e.eventId}}}async function ds(t,e){let n=`projects/${t.id}/work/observations/`,r=await e.list(n),s=[];for(let o of r.filter(i=>i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await e.getText(o.key);if(i)try{let a=JSON.parse(i);a.version===1&&Array.isArray(a.observations)&&s.push(a)}catch{}}return s}async function Re(t,e){let r=(await ds(t,e)).flatMap(h=>h.observations).sort((h,k)=>{let E=h.occurredAt.localeCompare(k.occurredAt);if(E!==0)return E;let V=h.sequence-k.sequence;return V!==0?V:h.id.localeCompare(k.id)}),s=new Map,o=new Map,i,a,c,u,p,l=[],f=[],d=[],m=[],S=[],g=new Map,y=[],v=[],x=[],O=[],P=[],T=[];for(let h of r)switch(h.kind){case"request":i=h.text;break;case"activity":a=h.text;break;case"goal":c=h.text;break;case"plan":u=h.text;break;case"phase":s.set(h.key,us(s.get(h.key),h));break;case"task":o.set(h.key,us(o.get(h.key),h));break;case"decision":l.push(h.text);break;case"blocker":f.push(h.text);break;case"warning":d.push(h.text);break;case"next_action":m.push(h.text);break;case"file":{S.push(h.text);let k=h.fileAction??"active";g.delete(h.text),g.set(h.text,k),k==="modified"?y.push(h.text):k==="created"?v.push(h.text):k==="deleted"&&x.push(h.text);break}case"command":O.push(h.text);break;case"test":P.push(h.text),h.checkKind&&T.push({kind:h.checkKind,command:h.text,status:h.checkStatus??"unknown",updatedAt:h.occurredAt,agent:h.agent,nativeSessionId:h.nativeSessionId});break;case"session":p={agent:h.agent,nativeSessionId:h.nativeSessionId,sessionKey:h.sessionKey,updatedAt:h.occurredAt};break}let j=Array.from(s.values()).sort((h,k)=>(h.order??Number.MAX_SAFE_INTEGER)-(k.order??Number.MAX_SAFE_INTEGER)),b=Array.from(o.values()).sort((h,k)=>(h.order??Number.MAX_SAFE_INTEGER)-(k.order??Number.MAX_SAFE_INTEGER)),D=j.find(h=>h.status==="in_progress")??j.find(h=>h.status==="blocked")??j.find(h=>h.status==="pending"),z=b.find(h=>h.status==="in_progress")??b.find(h=>h.status==="blocked")??b.find(h=>h.status==="pending"),Ot=F([...m,...z?[z.title]:[],...!z&&D?[D.title]:[],...b.filter(h=>h.status==="pending").slice(0,5).map(h=>h.title)],8),Tt=F([...f,...j.filter(h=>h.status==="blocked").map(h=>h.title),...b.filter(h=>h.status==="blocked").map(h=>h.title)],20),pe={version:1,projectId:t.id,projectName:t.name,currentRequest:i,currentActivity:a,goal:c,plan:u,phases:j,tasks:b,decisions:F(l,20),blockers:Tt,warnings:F(d,20),nextActions:Ot,filesTouched:F(S,30),activeFiles:Array.from(g.entries()).filter(([,h])=>h!=="deleted").map(([h])=>h).slice(-5),modifiedFiles:F(y,30),createdFiles:F(v,30),deletedFiles:F(x,30),commands:F(O,20),tests:F(P,20),checks:iu(T,20),currentPhase:D,currentTask:z,progress:{phasesTotal:j.length,phasesCompleted:j.filter(h=>h.status==="completed").length,tasksTotal:b.length,tasksCompleted:b.filter(h=>h.status==="completed").length,blocked:j.filter(h=>h.status==="blocked").length+b.filter(h=>h.status==="blocked").length},lastSession:p,updatedAt:r.length?r[r.length-1].occurredAt:new Date().toISOString()},$e=cs(t.rootPath,".toolnet","work");return ou($e,{recursive:!0}),R(cs($e,"current.json"),pe),await e.put(`projects/${t.id}/work/current.json`,JSON.stringify(pe,null,2)+`
|
|
52
|
+
`,"application/json"),pe}async function mt(t,e){if((await ds(t,e)).length>0)return Re(t,e);let r=await e.getText(`projects/${t.id}/work/current.json`);if(!r)return null;try{return JSON.parse(r)}catch{return null}}function fu(t,e){if(!uu(t))return{events:[],nextOffset:e};let n=pu(t).size,r=Number.isFinite(e)?Math.max(0,e):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=n-r,o=Buffer.alloc(s),i=lu(t,"r");try{du(i,o,0,s,r)}finally{cu(i)}let a=o.toString("utf8"),c=a.lastIndexOf(`
|
|
53
53
|
`);if(c<0)return{events:[],nextOffset:r};let u=a.slice(0,c+1);return{events:u.split(`
|
|
54
|
-
`).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var
|
|
55
|
-
`,"application/json"),c}};import{mkdirSync as
|
|
56
|
-
`,"application/json"),d}async function
|
|
54
|
+
`).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var gt=class{constructor(e){this.options=e;this.journal=new ft(e.storage)}options;journal;async learnNew(){let e=this.options.wal.loadState(),n=Number(e.sourceCursors["work.continuity.offset"]??0),r=fu(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=le(this.options.identity,r.events),o=!1,i=!1;return s.length>0&&(o=!!await this.journal.write(this.options.identity,s),o&&(await Re(this.options.project,this.options.storage),i=!0)),this.options.wal.setSourceCursor("work.continuity.offset",r.nextOffset),{scannedEvents:r.events.length,observations:s.length,journalWritten:o,reconciled:i,nextOffset:r.nextOffset}}};import{closeSync as bu,existsSync as xu,openSync as ju,readSync as Cu,statSync as Iu}from"node:fs";var mu=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function de(t){return t.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function on(t,e,n=0){if(!(n>6)){if(typeof t=="string"){e.push(t);return}if(Array.isArray(t)){for(let r of t.slice(0,50))on(r,e,n+1);return}if(!(!t||typeof t!="object"))for(let[r,s]of Object.entries(t))(mu.has(r)||["data","payload","parts","messages"].includes(r))&&on(s,e,n+1)}}function _(t,e,n,r,s,o=.95){let i=de(r);return{version:1,id:w([t.projectId,n,s.type,s.key??"",i.toLowerCase(),e.id].join("|")).slice(0,32),projectId:t.projectId,kind:n,value:i,scope:s.type,scopeKey:s.key,scopeOrder:s.order,confidence:o,evidence:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,eventId:e.id,sourceEventId:e.sourceEventId,sequence:e.sequence,occurredAt:e.timestamp}}}function L(t,e){let n=t.toLowerCase();for(let r of e){let s=r.toLowerCase();if(n.startsWith(`${s}:`)||n.startsWith(`${s} -`)||n.startsWith(`${s} \u2014`))return de(t.slice(r.length+1))}return null}function gu(t){let e=t.trimStart();return e.startsWith("- ")||e.startsWith("* ")||/^\d+[.)]\s+/u.test(e)}function yu(t){return de(t.trim().replace(/^[-*]\s+/u,"").replace(/^\d+[.)]\s+/u,""))}function ps(t,e){let n=[],r=new Set;function s(o){!o.value||o.value.length<3||r.has(o.id)||(r.add(o.id),n.push(o))}for(let o of e){let i=[];on(o.data,i);for(let a of i){let c={type:"project"},u=null;for(let p of a.split(/\r?\n/u)){let l=de(p);if(!l){u=null;continue}let f=l.match(/^(?:phase|giai đoạn|giai doan|stage)\s*(\d+)\s*(?:[:\-–—]\s*)?(.*)$/iu);if(f){let b=Number(f[1]);c={type:"phase",key:`phase:${b}`,order:b,title:de(f[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:de(d[2]??"")},u=null;continue}let m=L(l,["mission","s\u1EE9 m\u1EC7nh","m\u1EE5c ti\xEAu t\u1ED5ng th\u1EC3","m\u1EE5c ti\xEAu project","project goal"]);if(m){s(_(t,o,"mission",m,{type:"project"},.99)),u=null;continue}let S=L(l,["current objective","active objective","m\u1EE5c ti\xEAu hi\u1EC7n t\u1EA1i","objective","m\u1EE5c ti\xEAu","m\u1EE5c \u0111\xEDch"]);if(S){s(_(t,o,c.type==="phase"?"phase_objective":"objective",S,c,.98)),u=null;continue}let g=L(l,["why","why this","why this phase","reason","rationale","v\xEC sao","l\xFD do","t\u1EA1i sao","\xFD ngh\u0129a"]);if(g){s(_(t,o,c.type==="phase"?"phase_why":"why",g,c,.98)),u=null;continue}let y=L(l,["desired outcome","final outcome","k\u1EBFt qu\u1EA3 cu\u1ED1i","k\u1EBFt qu\u1EA3 mong mu\u1ED1n","m\u1EE5c ti\xEAu cu\u1ED1i"]);if(y){s(_(t,o,"desired_outcome",y,{type:"project"},.98)),u=null;continue}let v=L(l,["plan rationale","approach rationale","why this approach","t\u1EA1i sao ch\u1ECDn h\u01B0\u1EDBng n\xE0y","l\xFD do ch\u1ECDn h\u01B0\u1EDBng n\xE0y","l\xFD do ch\u1ECDn ki\u1EBFn tr\xFAc"]);if(v){s(_(t,o,"plan_rationale",v,{type:"project"},.98)),u=null;continue}let x=L(l,["deliverable","output","k\u1EBFt qu\u1EA3 c\u1EA7n \u0111\u1EA1t","ph\u1EA3i t\u1EA1o ra","\u0111\u1EA7u ra"]);if(x){s(_(t,o,"phase_deliverable",x,c,.97)),u=null;continue}let O=L(l,["acceptance criteria","definition of done","done khi","ho\xE0n th\xE0nh khi","ti\xEAu ch\xED ho\xE0n th\xE0nh"]);if(O){s(_(t,o,"acceptance_criterion",O,c,.98)),u="acceptance_criterion";continue}let P=L(l,["depends on","dependency","dependencies","ph\u1EE5 thu\u1ED9c","c\u1EA7n c\xF3 tr\u01B0\u1EDBc"]);if(P){s(_(t,o,"dependency",P,c,.97)),u="dependency";continue}let T=L(l,["open question","open questions","c\xE2u h\u1ECFi m\u1EDF","ch\u01B0a quy\u1EBFt \u0111\u1ECBnh","ch\u01B0a r\xF5"]);if(T){s(_(t,o,"open_question",T,c,.95)),u="open_question";continue}let j=L(l,["constraint","constraints","r\xE0ng bu\u1ED9c","gi\u1EDBi h\u1EA1n"]);if(j){s(_(t,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&&gu(p)){s(_(t,o,u,yu(p),c,.96));continue}u=null}}}return n}function fs(t){return String(t).padStart(12,"0")}var yt=class{constructor(e){this.storage=e}storage;async write(e,n){if(n.length===0)return null;let r=Math.min(...n.map(u=>u.evidence.sequence)),s=Math.max(...n.map(u=>u.evidence.sequence)),o={version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,firstSequence:r,lastSequence:s,createdAt:new Date().toISOString(),observations:n},i=w(n.map(u=>u.id).sort().join("|")).slice(0,16),a=w(e.sessionKey).slice(0,12),c=[`projects/${e.projectId}`,"work","semantic","observations",`${fs(r)}-${fs(s)}-${a}-${i}.json`].join("/");return await this.storage.exists(c)||await this.storage.put(c,JSON.stringify(o,null,2)+`
|
|
55
|
+
`,"application/json"),c}};import{mkdirSync as hu}from"node:fs";import{join as ms}from"node:path";function Su(t){return{value:t.value,confidence:t.confidence,evidence:t.evidence}}function ku(t,e){if(!e)return!0;let n=t.evidence.occurredAt.localeCompare(e.evidence.occurredAt);return n!==0?n>0:t.evidence.sessionKey===e.evidence.sessionKey?t.evidence.sequence>=e.evidence.sequence:t.confidence>=e.confidence}function G(t,e){return ku(e,t)?e:t}function U(t,e=30){let n=new Set,r=[];for(let s of t){let o=s.value.normalize("NFKC").toLowerCase().replace(/\s+/g," ").trim();!o||n.has(o)||(n.add(o),r.push(s))}return r.slice(-e)}async function vu(t,e){let n=`projects/${t.id}/work/semantic/observations/`,r=await e.list(n),s=[];for(let o of r.filter(i=>i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await e.getText(o.key);if(i)try{let a=JSON.parse(i);a.version===1&&Array.isArray(a.observations)&&s.push(a)}catch{}}return s}function wu(t){return{key:t.scopeKey??`phase:${t.scopeOrder??0}`,order:t.scopeOrder??0,acceptanceCriteria:[],dependencies:[],openQuestions:[],constraints:[],notes:[]}}async function gs(t,e){let r=(await vu(t,e)).flatMap(S=>S.observations).sort((S,g)=>{let y=S.evidence.occurredAt.localeCompare(g.evidence.occurredAt);return y!==0?y:S.evidence.sessionKey===g.evidence.sessionKey?S.evidence.sequence-g.evidence.sequence:S.id.localeCompare(g.id)}),s,o,i,a,c,u=new Map,p=[],l=[],f=[];for(let S of r){let g=Su(S);if(S.scope==="phase"&&S.scopeKey){let y=u.get(S.scopeKey)??wu(S);switch(S.kind){case"phase_objective":y.objective=G(y.objective,g);break;case"phase_why":y.why=G(y.why,g);break;case"phase_deliverable":y.deliverable=G(y.deliverable,g);break;case"acceptance_criterion":y.acceptanceCriteria.push(g);break;case"dependency":y.dependencies.push(g);break;case"open_question":y.openQuestions.push(g);break;case"constraint":y.constraints.push(g);break;case"note":y.notes.push(g);break}u.set(y.key,y);continue}switch(S.kind){case"mission":s=G(s,g);break;case"objective":o=G(o,g);break;case"why":i=G(i,g);break;case"desired_outcome":a=G(a,g);break;case"plan_rationale":c=G(c,g);break;case"open_question":p.push(g);break;case"constraint":l.push(g);break;case"note":f.push(g);break}}for(let S of u.values())S.acceptanceCriteria=U(S.acceptanceCriteria,20),S.dependencies=U(S.dependencies,15),S.openQuestions=U(S.openQuestions,15),S.constraints=U(S.constraints,15),S.notes=U(S.notes,20);let d={version:1,projectId:t.id,projectName:t.name,mission:s,activeObjective:o,why:i,desiredOutcome:a,planRationale:c,phases:Array.from(u.values()).sort((S,g)=>S.order-g.order),openQuestions:U(p,20),constraints:U(l,20),notes:U(f,20),updatedAt:r.length?r[r.length-1].evidence.occurredAt:new Date().toISOString()},m=ms(t.rootPath,".toolnet","work");return hu(m,{recursive:!0}),R(ms(m,"semantic-current.json"),d),await e.put(`projects/${t.id}/work/semantic/current.json`,JSON.stringify(d,null,2)+`
|
|
56
|
+
`,"application/json"),d}async function ys(t,e){let n=await e.getText(`projects/${t.id}/work/semantic/current.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}function Au(t,e){if(!xu(t))return{events:[],nextOffset:e};let n=Iu(t).size,r=Number.isFinite(e)?Math.max(0,e):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=Buffer.alloc(n-r),o=ju(t,"r");try{Cu(o,s,0,s.length,r)}finally{bu(o)}let i=s.toString("utf8"),a=i.lastIndexOf(`
|
|
57
57
|
`);if(a<0)return{events:[],nextOffset:r};let c=i.slice(0,a+1);return{events:c.split(`
|
|
58
|
-
`).filter(Boolean).flatMap(u=>{try{return[JSON.parse(u)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(c,"utf8")}}var
|
|
58
|
+
`).filter(Boolean).flatMap(u=>{try{return[JSON.parse(u)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(c,"utf8")}}var ht=class{constructor(e){this.options=e;this.journal=new yt(e.storage)}options;journal;async learnNew(){let e=this.options.wal.loadState(),n=Number(e.sourceCursors["work.semantic.offset"]??0),r=Au(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=ps(this.options.identity,r.events),o=!1,i=!1;return s.length>0&&(o=!!await this.journal.write(this.options.identity,s),o&&(await gs(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 vl,mkdirSync as wl}from"node:fs";import{join as cn}from"node:path";import{existsSync as ks,mkdirSync as Mu,readFileSync as Pu,statSync as hs,writeFileSync as Eu}from"node:fs";import{dirname as Ou,join as Tu}from"node:path";var Ss=64*1024,Ru=`# ToolNet Project Operating Manual
|
|
59
59
|
|
|
60
60
|
This file contains persistent instructions for AI agents working on this project.
|
|
61
61
|
|
|
@@ -98,52 +98,52 @@ Things an AI agent should always remember.
|
|
|
98
98
|
<!--
|
|
99
99
|
- [advisory] Prefer small focused files.
|
|
100
100
|
-->
|
|
101
|
-
`;function
|
|
102
|
-
`,{encoding:"utf8"}),
|
|
103
|
-
`,{encoding:"utf8"}),
|
|
104
|
-
`).toLowerCase();return/(?:failed|failing|failure|error|✗|❌)/u.test(r)?"failing":/(?:passed|passing|green|success|✓|✅)/u.test(r)?"passing":"unknown"}function
|
|
101
|
+
`;function St(t){return Tu(t.rootPath,".toolnet","PROJECT.md")}function Nu(t){return t.normalize("NFKC").replace(/\s+/g," ").trim()}function _u(t){let e=[],n=new Set,r=/^\s*[-*]\s+\[(enforce|advisory)\]\s+(.+?)\s*$/gimu,s;for(;s=r.exec(t);){let o=s[1].toLowerCase(),i=Nu(s[2]);if(!i)continue;let a=`${o}:${i.toLowerCase()}`;n.has(a)||(n.add(a),e.push({id:w(a).slice(0,24),mode:o,text:i,source:"manual"}))}return e}function $u(t){let e=St(t);return ks(e)||(Mu(Ou(e),{recursive:!0}),Eu(e,Ru,{encoding:"utf8",mode:384})),e}function kt(t,e=!1){let n=e?$u(t):St(t);if(!ks(n))return null;if(hs(n).size>Ss)throw new Error(`PROJECT.md exceeds ${Ss} bytes`);let s=Pu(n,"utf8");return{path:n,content:s,digest:w(s),rules:_u(s),bytes:Buffer.byteLength(s,"utf8"),updatedAt:new Date(hs(n).mtimeMs).toISOString()}}import{randomUUID as Ku}from"node:crypto";import{closeSync as Fu,existsSync as vs,fsyncSync as Lu,mkdirSync as Wu,openSync as Du,readFileSync as zu,statSync as qu,unlinkSync as ws,writeFileSync as Vu}from"node:fs";import{dirname as Hu,join as Bu}from"node:path";var Ju=new Int32Array(new SharedArrayBuffer(4));function Gu(t){t<=0||Atomics.wait(Ju,0,0,t)}function Uu(t){return Bu(t.rootPath,".toolnet","work",".current.lock")}function Yu(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e?.code!=="ESRCH"}}function bs(t){if(!vs(t))return null;try{let e=JSON.parse(zu(t,"utf8"));return e.version!==1||typeof e.token!="string"||typeof e.pid!="number"||typeof e.acquiredAt!="string"?null:{version:1,token:e.token,pid:e.pid,acquiredAt:e.acquiredAt}}catch{return null}}function Xu(t){try{return Date.now()-qu(t).mtimeMs}catch{return 0}}function Qu(t,e){if(!vs(t)||Xu(t)<e)return!1;let n=bs(t);return n?!Yu(n.pid):!0}function Zu(t,e){if(!Qu(t,e))return!1;try{return ws(t),!0}catch{return!1}}function el(t,e){let n={version:1,token:e,pid:process.pid,acquiredAt:new Date().toISOString()},r=Du(t,"wx",384);try{Vu(r,`${JSON.stringify(n,null,2)}
|
|
102
|
+
`,{encoding:"utf8"}),Lu(r)}finally{Fu(r)}}function tl(t,e){if(bs(t)?.token===e)try{ws(t)}catch{}}function nl(t,e={}){let n=Math.max(100,e.timeoutMs??5e3),r=Math.max(5,e.retryMs??20),s=Math.max(n*2,e.staleMs??3e4),o=Uu(t);Wu(Hu(o),{recursive:!0});let i=Ku(),a=Date.now()+n;for(;;)try{el(o,i);let c=!1;return()=>{c||(c=!0,tl(o,i))}}catch(c){if(c?.code!=="EEXIST")throw c;if(Zu(o,s))continue;if(Date.now()>=a)throw new Error(`Timed out acquiring project work lock: ${o}`);Gu(r)}}function xs(t,e,n={}){let r=nl(t,n);try{return e()}finally{r()}}import{closeSync as rl,existsSync as sl,fsyncSync as ol,mkdirSync as il,openSync as al,readFileSync as cl,renameSync as ul,writeFileSync as ll}from"node:fs";import{dirname as dl,join as pl}from"node:path";function fl(t,e){il(dl(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`,r=al(n,"w",384);try{ll(r,`${JSON.stringify(e,null,2)}
|
|
103
|
+
`,{encoding:"utf8"}),ol(r)}finally{rl(r)}ul(n,t)}function Ps(t){return pl(t.rootPath,".toolnet","work","current.json")}function an(t){let e=Ps(t);if(!sl(e))return null;try{let n=JSON.parse(cl(e,"utf8"));return n.version!==1||n.projectId!==t.id?null:n}catch{return null}}function vt(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function $(t,e,n){let r=[],s=new Set;for(let o of[...t,...e].reverse()){let i=vt(o);if(!(!i||s.has(i))&&(s.add(i),r.push(o),r.length>=n))break}return r.reverse()}function ml(t,e,n=20){let r=new Map;for(let s of[...t,...e]){let o=`${s.kind}|${vt(s.command)}`;r.delete(o),r.set(o,s)}return Array.from(r.values()).slice(-n)}function gl(t){return t.kind==="phase"?/^Phase\s+\d+$/iu.test(t.text):t.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(t.text):!1}function js(t,e){let n=e.status??t?.status??"pending",r=n;t?.status==="completed"&&n!=="completed"&&(r="completed"),t&&n==="pending"&&(t.status==="in_progress"||t.status==="blocked")&&(r=t.status);let s=t&&gl(e)?t.title:e.text;return{id:t?.id??e.id,title:s,status:r,order:e.order??t?.order,confidence:Math.max(t?.confidence??0,e.confidence),updatedAt:e.occurredAt,updatedBy:{agent:e.agent,nativeSessionId:e.nativeSessionId,eventId:e.eventId}}}function Cs(t){let e=new Map;for(let n of t){let r=n.order!==void 0?`order:${n.order}`:vt(n.title);e.set(r,n)}return e}function Is(t){return t.order!==void 0?`order:${t.order}`:vt(t.key||t.text)}function As(t){return Array.from(t).sort((e,n)=>{let r=e.order??Number.MAX_SAFE_INTEGER,s=n.order??Number.MAX_SAFE_INTEGER;return r!==s?r-s:e.updatedAt.localeCompare(n.updatedAt)})}function Ms(t){return t.find(e=>e.status==="in_progress")??t.find(e=>e.status==="blocked")??t.find(e=>e.status==="pending")}function yl(t,e){let n=an(t),r=Cs(n?.phases??[]),s=Cs(n?.tasks??[]),o=n?.currentRequest,i=n?.currentActivity,a=n?.goal,c=n?.plan,u=n?.lastSession,p=[],l=[],f=[],d=[],m=[],S=[...n?.activeFiles??[]],g=[],y=[],v=[],x=[],O=[],P=[],T=[...e].sort((k,E)=>{let V=k.occurredAt.localeCompare(E.occurredAt);return V!==0?V:k.sequence-E.sequence});for(let k of T)switch(k.kind){case"request":o=k.text;break;case"activity":i=k.text;break;case"goal":a=k.text;break;case"plan":c=k.text;break;case"phase":{let E=Is(k);r.set(E,js(r.get(E),k));break}case"task":{let E=Is(k);s.set(E,js(s.get(E),k));break}case"decision":p.push(k.text);break;case"blocker":l.push(k.text);break;case"warning":f.push(k.text);break;case"next_action":d.push(k.text);break;case"file":{m.push(k.text);let E=k.fileAction??"active",V=S.indexOf(k.text);V>=0&&S.splice(V,1),E!=="deleted"&&S.push(k.text),E==="modified"?g.push(k.text):E==="created"?y.push(k.text):E==="deleted"&&v.push(k.text);break}case"command":x.push(k.text);break;case"test":O.push(k.text),k.checkKind&&P.push({kind:k.checkKind,command:k.text,status:k.checkStatus??"unknown",updatedAt:k.occurredAt,agent:k.agent,nativeSessionId:k.nativeSessionId});break;case"session":u={agent:k.agent,nativeSessionId:k.nativeSessionId,sessionKey:k.sessionKey,updatedAt:k.occurredAt};break}let j=As(r.values()),b=As(s.values()),D=Ms(j),z=Ms(b),Ot=$(n?.nextActions??[],[...d,...z?[z.title]:[],...!z&&D?[D.title]:[],...b.filter(k=>k.status==="pending").slice(0,5).map(k=>k.title)],8),Tt=$(n?.blockers??[],[...l,...j.filter(k=>k.status==="blocked").map(k=>k.title),...b.filter(k=>k.status==="blocked").map(k=>k.title)],20),pe=T.length>0?T[T.length-1].occurredAt:n?.updatedAt??new Date().toISOString(),$e={version:1,projectId:t.id,projectName:t.name,currentRequest:o,currentActivity:i,goal:a,plan:c,phases:j,tasks:b,decisions:$(n?.decisions??[],p,20),blockers:Tt,warnings:$(n?.warnings??[],f,20),nextActions:Ot,filesTouched:$(n?.filesTouched??[],m,30),activeFiles:$([],S,5),modifiedFiles:$(n?.modifiedFiles??[],g,30),createdFiles:$(n?.createdFiles??[],y,30),deletedFiles:$(n?.deletedFiles??[],v,30),commands:$(n?.commands??[],x,20),tests:$(n?.tests??[],O,20),checks:ml(n?.checks??[],P,20),currentPhase:D,currentTask:z,progress:{phasesTotal:j.length,phasesCompleted:j.filter(k=>k.status==="completed").length,tasksTotal:b.length,tasksCompleted:b.filter(k=>k.status==="completed").length,blocked:j.filter(k=>k.status==="blocked").length+b.filter(k=>k.status==="blocked").length},lastSession:u,updatedAt:pe},h=ye($e);return fl(Ps(t),h),h}function wt(t,e){return xs(t,()=>yl(t,e))}function M(t,e){let n=new Set,r=[];for(let s of t){let o=s.replace(/\s+/g," ").trim();if(!o)continue;let i=o.normalize("NFKC").toLowerCase();if(!n.has(i)&&(n.add(i),r.push(o),r.length>=e))break}return r}function Es(t){if(t)return{id:t.id,title:t.title,status:t.status}}function hl(t,e=[]){let n=e.slice(-10);if(n.some(s=>s.status==="failed"))return"failing";if(n.some(s=>s.status==="passed"))return"passing";let r=t.slice(-10).join(`
|
|
104
|
+
`).toLowerCase();return/(?:failed|failing|failure|error|✗|❌)/u.test(r)?"failing":/(?:passed|passing|green|success|✓|✅)/u.test(r)?"passing":"unknown"}function Sl(t){return w(JSON.stringify(t))}function kl(t){let e=[];for(let n of t){if(!n)continue;let r=n.match(/https?:\/\/[^\s<>"'`)\]}]+/giu)??[];for(let s of r){let o=s.replace(/[.,;:!?]+$/gu,"").trim();o&&e.push(o)}}return M(e,30)}function Os(t){let{project:e,identity:n,state:r}=t,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())),p=M(r.nextActions.filter(v=>!u.has(v.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),10),l=M([...c,...p],15),f=M(r.tests.slice().reverse(),10),d=M([...(r.activeFiles??[]).slice().reverse(),...r.filesTouched.slice().reverse()],20),m={schema:"toolnet.handoff.v2",version:2,project:{id:e.id,name:e.name},source:{agent:n.agent,nativeSessionId:n.nativeSessionId,sessionKey:n.sessionKey,sequence:t.sequence,reason:t.reason},capturedAt:t.capturedAt??new Date().toISOString(),goal:r.goal,request:r.currentRequest,activity:r.currentActivity,current:{phase:Es(r.currentPhase),task:Es(r.currentTask),file:s},completed:{phases:M(o,20),tasks:M(i,30)},remaining:{phases:M(a,20),tasks:M(c,30),todos:l},nextAction:p[0],blockers:M(r.blockers.slice().reverse(),10),decisions:M(r.decisions.slice().reverse(),10),files:{current:s,recent:d,active:M(r.activeFiles??[],10),modified:M(r.modifiedFiles??[],20),created:M(r.createdFiles??[],20),deleted:M(r.deletedFiles??[],20)},tests:{status:hl(r.tests,r.checks),recent:f,checks:(r.checks??[]).slice(-10).map(v=>({kind:v.kind,status:v.status,command:v.command}))},evidence:{commands:M((r.commands??[]).slice().reverse(),20),references:kl([r.currentRequest,r.currentActivity,r.goal,r.plan,...r.decisions,...r.blockers,...r.warnings,...r.nextActions,...r.filesTouched,...r.commands??[],...r.tests,...(r.checks??[]).map(v=>v.command)])},attention:M(t.attention??[],20),progress:r.progress},{capturedAt:S,source:g,...y}=m;return{...m,stateDigest:Sl(y)}}function bl(t){return!!(t.currentRequest||t.currentActivity||t.goal||t.plan||t.phases.length>0||t.tasks.length>0||t.nextActions.length>0||t.blockers.length>0||t.decisions.length>0||t.filesTouched.length>0)}function Ts(t,e,n,r,s){if(!bl(n))return null;let o=kt(t,!1),a=[...o?o.rules.filter(l=>l.mode==="enforce").map(l=>l.text):[],...n.warnings].slice(0,20),c=Os({project:t,identity:e,state:n,reason:r,sequence:s,attention:a}),u=c.stateDigest;return{version:1,id:w([t.id,e.sessionKey,u].join("|")).slice(0,24),projectId:t.id,projectName:t.name,createdAt:new Date().toISOString(),reason:r,sourceSession:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,sequence: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 Rs(t,e){let n=cn(t.rootPath,".toolnet","work","handoffs");wl(n,{recursive:!0});let r=cn(n,`${e.id}.json`);vl(r)||R(r,e),R(cn(t.rootPath,".toolnet","work","handoff-latest.json"),e)}function Ns(t){let e=Ts(t.project,t.identity,t.state,t.reason,t.sequence);return e?(Rs(t.project,e),e):null}var bt=class{constructor(e){this.options=e}options;async capture(e,n){let r=an(this.options.project);r||(r=await mt(this.options.project,this.options.storage)),r||(r=await Re(this.options.project,this.options.storage));let s=Ts(this.options.project,this.options.identity,r,e,n);if(!s)return null;Rs(this.options.project,s);let o=`projects/${this.options.project.id}/work/handoffs/${s.id}.json`;return await this.options.storage.exists(o)||await this.options.storage.put(o,JSON.stringify(s,null,2)+`
|
|
105
105
|
`,"application/json"),await this.options.storage.put(`projects/${this.options.project.id}/work/handoff-latest.json`,JSON.stringify(s,null,2)+`
|
|
106
|
-
`,"application/json"),s}};async function
|
|
107
|
-
`)}function
|
|
106
|
+
`,"application/json"),s}};async function _s(t,e){let n=await e.getText(`projects/${t.id}/work/handoff-latest.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}import{existsSync as xl,readFileSync as jl,writeFileSync as Cl}from"node:fs";import{join as Il}from"node:path";var Ks="<!-- TOOLNET:STABLE-WORK:BEGIN -->",un="<!-- TOOLNET:STABLE-WORK:END -->";function ln(t){switch(t.status){case"completed":return"[x]";case"in_progress":return"[~]";case"blocked":return"[!]";case"cancelled":return"[-]";default:return"[ ]"}}function W(t,e){return e.length?["",`${t}:`,...e.map(n=>`- ${n}`)]:[]}function $s(t,e){return e.length?["",`${t}:`,...e.map(n=>`- ${ln(n)} ${n.title}`)]:[]}function Al(t){let e=[Ks,"# ToolNet Stable Work State","",`Updated: ${t.updatedAt}`];return t.lastSession&&e.push(`Last agent: ${t.lastSession.agent}`,`Last session: ${t.lastSession.nativeSessionId}`),t.currentRequest&&e.push("","Current request:",t.currentRequest),t.currentActivity&&e.push("","Current activity:",t.currentActivity),t.goal&&e.push("","Goal:",t.goal),t.plan&&e.push("","Plan:",t.plan),t.currentPhase&&e.push("","Current phase:",`${ln(t.currentPhase)} ${t.currentPhase.title}`),t.currentTask&&e.push("","Current task:",`${ln(t.currentTask)} ${t.currentTask.title}`),e.push(...$s("Phases",t.phases)),e.push(...$s("TODO / Tasks",t.tasks)),e.push(...W("Next actions",t.nextActions)),e.push(...W("Blockers",t.blockers)),e.push(...W("Important decisions",t.decisions)),e.push(...W("Active files",t.activeFiles??[])),e.push(...W("Modified files",t.modifiedFiles??[])),e.push(...W("Created files",t.createdFiles??[])),e.push(...W("Deleted files",t.deletedFiles??[])),e.push(...W("Files touched",t.filesTouched)),e.push(...W("Recent commands",t.commands??[])),e.push(...W("Checks",(t.checks??[]).map(n=>`[${n.status}] ${n.kind}: ${n.command}`))),e.push("","Progress:",`- Phases: ${t.progress.phasesCompleted}/${t.progress.phasesTotal}`,`- Tasks: ${t.progress.tasksCompleted}/${t.progress.tasksTotal}`,`- Blocked: ${t.progress.blocked}`,"","Continuation:","- Resume current unfinished task.","- Never redo completed TODO/Phase unless explicitly requested.","- Ask ToolNet Memory for deeper history only when necessary.",un),e.join(`
|
|
107
|
+
`)}function xt(t,e){let n=Il(t.rootPath,".toolnet","current.md"),r="";if(xl(n))try{r=jl(n,"utf8")}catch{r=""}r=r.replace(/<!-- TOOLNET:AUTO-CURRENT:BEGIN -->[\s\S]*?<!-- TOOLNET:AUTO-CURRENT:END -->/gu,"");let s=Al(e),o=r.indexOf(Ks),i=r.indexOf(un),a;o>=0&&i>=o?a=[r.slice(0,o).trimEnd(),s,r.slice(i+un.length).trimStart()].filter(Boolean).join(`
|
|
108
108
|
|
|
109
109
|
`):a=r.trim()?`${r.trim()}
|
|
110
110
|
|
|
111
|
-
${s}`:s,
|
|
112
|
-
`,{encoding:"utf8",mode:384})}import{existsSync as
|
|
113
|
-
`,{encoding:"utf8",mode:384}),
|
|
114
|
-
`)}import{existsSync as
|
|
115
|
-
`))if(n)try{let r=
|
|
111
|
+
${s}`:s,Cl(n,`${a.trim()}
|
|
112
|
+
`,{encoding:"utf8",mode:384})}import{existsSync as Ml,mkdirSync as Pl,readFileSync as El,renameSync as Ol,writeFileSync as Tl}from"node:fs";import{dirname as Rl,join as Nl}from"node:path";function Fs(t){return Nl(t.rootPath,".toolnet","context","session-origin.json")}function _l(t,e){Pl(Rl(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`;Tl(n,`${JSON.stringify(e,null,2)}
|
|
113
|
+
`,{encoding:"utf8",mode:384}),Ol(n,t)}function jt(t,e){return[...t].filter(n=>n.kind===e).sort((n,r)=>{let s=n.occurredAt.localeCompare(r.occurredAt);return s!==0?s:n.sequence-r.sequence}).at(-1)}function Ct(t,e){let n=jt(e.observations,"file"),r=jt(e.observations,"next_action"),s=jt(e.observations,"blocker"),o=jt(e.observations,"decision"),i={version:1,projectId:t.id,agent:e.agent,nativeSessionId:e.nativeSessionId,updatedAt:e.workState.updatedAt,currentRequest:e.workState.currentRequest,currentActivity:e.workState.currentActivity,currentTask:e.workState.currentTask?.title,currentPhase:e.workState.currentPhase?.title,lastTouchedFile:n?.text??e.workState.activeFiles?.at(-1)??e.workState.filesTouched.at(-1),latestNextAction:r?.text??e.workState.nextActions.at(-1),latestBlocker:s?.text??e.workState.blockers.at(-1),latestDecision:o?.text??e.workState.decisions.at(-1)};return _l(Fs(t),i),i}function $l(t){let e=Fs(t);if(!Ml(e))return null;try{let n=JSON.parse(El(e,"utf8"));return n.version!==1||n.projectId!==t.id?null:n}catch{return null}}function Ls(t){let e=$l(t);if(!e)return null;let n=["Previous session:",`- Agent: ${e.agent}`,`- Session: ${e.nativeSessionId}`];return e.currentRequest&&n.push(`- Current request: ${e.currentRequest}`),e.currentActivity&&n.push(`- Current activity: ${e.currentActivity}`),e.currentPhase&&n.push(`- Current phase: ${e.currentPhase}`),e.currentTask&&n.push(`- Current task: ${e.currentTask}`),e.lastTouchedFile&&n.push(`- Last touched file: ${e.lastTouchedFile}`),e.latestBlocker&&n.push(`- Blocker: ${e.latestBlocker}`),e.latestNextAction&&n.push(`- Next action: ${e.latestNextAction}`),e.latestDecision&&n.push(`- Important decision: ${e.latestDecision}`),n.join(`
|
|
114
|
+
`)}import{existsSync as Ws,mkdirSync as Kl,readFileSync as Fl}from"node:fs";import{join as dn}from"node:path";function Ds(t){return dn(t.rootPath,".toolnet","memory","checkpoints")}function zs(t){return dn(Ds(t),"latest.json")}function Ll(t){let e=zs(t);if(!Ws(e))return null;try{let n=JSON.parse(Fl(e,"utf8"));return n.schema!=="toolnet.memory.checkpoint.v1"||n.project.id!==t.id?null:n}catch{return null}}function Wl(t){return["rule","architecture","decision","fix"].includes(t)}function Dl(t,e){return e.length===0?[]:nt(t,e).candidates.filter(r=>Wl(r.kind)&&r.knowledgeClass!=="transient"&&r.importanceScore>=.65).map(r=>({fingerprint:r.fingerprint,kind:r.kind,content:r.content,knowledgeClass:r.knowledgeClass,importanceScore:r.importanceScore,confidence:r.confidence,createdAt:r.createdAt,agent:t.agent,nativeSessionId:t.nativeSessionId}))}function zl(t,e){let n=new Map;for(let r of[...t,...e]){let s=n.get(r.fingerprint);(!s||r.importanceScore>s.importanceScore)&&n.set(r.fingerprint,r)}return Array.from(n.values()).sort((r,s)=>s.importanceScore-r.importanceScore||s.createdAt.localeCompare(r.createdAt)).slice(0,80)}function ql(t){return{request:t.currentRequest,activity:t.currentActivity,goal:t.goal,phase:t.currentPhase?{title:t.currentPhase.title,status:t.currentPhase.status}:void 0,task:t.currentTask?{title:t.currentTask.title,status:t.currentTask.status}:void 0,phases:t.phases.map(e=>({title:e.title,status:e.status})),tasks:t.tasks.map(e=>({title:e.title,status:e.status})),activeFiles:t.activeFiles??[],modifiedFiles:t.modifiedFiles??[],createdFiles:t.createdFiles??[],deletedFiles:t.deletedFiles??[],checks:t.checks??[],blockers:t.blockers,decisions:t.decisions,nextActions:t.nextActions}}function qs(t,e,n,r){let s=Ll(t),o=zl(s?.durableFacts??[],Dl(e,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),p=r.tasks.filter(g=>g.status!=="completed"&&g.status!=="cancelled").map(g=>g.title),l={work:ql(r),durableFacts:o.map(g=>g.fingerprint).sort()},f=w(JSON.stringify(l)).slice(0,32),d={schema:"toolnet.memory.checkpoint.v1",version:1,project:{id:t.id,name:t.name},source:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,sequence:i},capturedAt:new Date().toISOString(),request:r.currentRequest,activity:r.currentActivity,goal:r.goal,current:{phase:r.currentPhase,task:r.currentTask},completed:{phases:a,tasks:c},remaining:{phases:u,tasks:p},files:{active:r.activeFiles??[],modified:r.modifiedFiles??[],created:r.createdFiles??[],deleted:r.deletedFiles??[]},checks:r.checks??[],blockers:r.blockers.slice(-10),decisions:r.decisions.slice(-15),nextActions:r.nextActions.slice(0,10),durableFacts:o,stateDigest:f},m=Ds(t);Kl(m,{recursive:!0,mode:448});let S=dn(m,`${f}.json`);return Ws(S)||R(S,d),R(zs(t),d),d}function Vs(t,e,n){if(process.env.TOOLNET_LOCAL_CHECKPOINT==="0"||n.length===0)return{updated:!1,observations:0};let r=le(e,n);if(r.length===0)return{updated:!1,observations:0};let s=wt(t,r);xt(t,s),Ct(t,{agent:e.agent,nativeSessionId:e.nativeSessionId,observations:r,workState:s});try{qs(t,e,n,s)}catch{}try{Ns({project:t,identity:e,state:s,reason:"continuous-checkpoint",sequence:n.at(-1)?.sequence??0})}catch{}return{updated:!0,observations:r.length}}var It=class{identity;wal;remote;sanitizer=new H;learner;continuity;semantic;handoff;project;title;metadata;constructor(e){this.project=e.project,this.identity=Ve(e.project,e.agent,e.nativeSessionId),this.title=e.title,this.metadata=this.sanitizer.sanitizeValue(e.metadata??{}),this.wal=new Xe(this.identity,e.eventContext),this.remote=new He(e.storage,e.maxEventsPerChunk??100,e.maxChunkBytes??512*1024),this.learner=new dt({project:e.project,storage:e.storage,identity:this.identity,wal:this.wal}),this.continuity=new gt({project:e.project,storage:e.storage,identity:this.identity,wal:this.wal}),this.semantic=new ht({project:e.project,storage:e.storage,identity:this.identity,wal:this.wal}),this.handoff=new bt({project:e.project,storage:e.storage,identity:this.identity})}sanitizeEvent(e){let n=e.provenance?{...e.provenance,metadata:this.sanitizer.sanitizeValue(e.provenance.metadata)}:void 0;return{...e,data:this.sanitizer.sanitizeValue(e.data??{}),provenance:n}}checkpointLocal(e){if(e.length!==0)try{Vs(this.project,this.identity,e)}catch{}}start(e={}){let n=this.wal.loadState();return this.record({type:n.lastSequence===0?"session_start":"session_resume",data:e,provenance:{source:this.identity.agent}})}record(e){let n=this.wal.append([this.sanitizeEvent(e)]);return this.checkpointLocal(n),n[0]}recordMany(e){let n=this.wal.append(e.map(r=>this.sanitizeEvent(r)));return this.checkpointLocal(n),n}setSourceCursor(e,n){this.wal.setSourceCursor(e,n)}async flush(){let e=this.wal.readPending(),n=this.wal.loadState(),r=await this.remote.append(this.identity,e.events,n.sourceCursors,{title:this.title,metadata:this.metadata});if(e.events.length>0){let s=e.events[e.events.length-1];this.wal.markRemote(s.sequence,e.endOffset)}if(process.env.TOOLNET_SESSION_LEARNING!=="0")try{await this.learner.learnNew()}catch{}if(process.env.TOOLNET_WORK_CONTINUITY!=="0")try{await this.continuity.learnNew()}catch{}if(process.env.TOOLNET_SEMANTIC_CONTINUITY!=="0")try{await this.semantic.learnNew()}catch{}if(process.env.TOOLNET_SMART_HANDOFF!=="0"&&e.events.length>0)try{let s=e.events[e.events.length-1],o=["session_idle","session_end","session_compact"].includes(s.type)?s.type:"checkpoint";await this.handoff.capture(o,s.sequence)}catch{}return r}async idle(e={}){return this.record({type:"session_idle",data:e,provenance:{source:this.identity.agent}}),this.flush()}async end(e={}){return this.record({type:"session_end",data:e,provenance:{source:this.identity.agent}}),this.flush()}status(){return this.wal.loadState()}recoverRemote(){return this.remote.recover(this.identity)}};import{existsSync as Vl,readFileSync as Hl,readdirSync as Bl,statSync as Hs}from"node:fs";import{homedir as Jl}from"node:os";import{join as At,resolve as Bs}from"node:path";function Js(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Gl(){return process.env.CODEX_HOME??At(Jl(),".codex")}function Ne(t){let e="";try{e=Hl(t,"utf8").slice(0,128*1024)}catch{return{raw:{}}}for(let n of e.split(`
|
|
115
|
+
`))if(n)try{let r=Js(JSON.parse(n));if(r.type!=="session_meta")continue;let s=Js(r.payload),o=[s.id,s.thread_id,s.threadId,s.session_id,s.sessionId].find(a=>typeof a=="string"),i=typeof s.cwd=="string"?s.cwd:void 0;return{threadId:o,cwd:i,raw:s}}catch{}return{raw:{}}}function pn(t,e){if(!Vl(t))return;let n;try{n=Bl(t,{withFileTypes:!0})}catch{return}for(let r of n){let s=At(t,r.name);if(r.isDirectory()){pn(s,e);continue}r.isFile()&&r.name.endsWith(".jsonl")&&e.push(s)}}function fn(){let t=Gl(),e=[];return pn(At(t,"sessions"),e),pn(At(t,"archived_sessions"),e),e.sort((n,r)=>{try{return Hs(r).mtimeMs-Hs(n).mtimeMs}catch{return 0}})}function mn(t){let e=fn(),n=e.find(r=>r.includes(t));if(n)return n;for(let r of e)if(Ne(r).threadId===t)return r;return null}function Mt(t,e){let n=Bs(t),r=Bs(e);return r===n||r.startsWith(n+"/")||n.startsWith(r+"/")}import{closeSync as Ul,existsSync as Yl,openSync as Xl,readSync as Ql,statSync as Zl}from"node:fs";function Gs(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ed(t){let e=t.timestamp;if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return new Date().toISOString()}function td(t){let e=typeof t.type=="string"?t.type.toLowerCase():"",n=Gs(t.payload),r=typeof n.type=="string"?n.type.toLowerCase():"",s=typeof n.role=="string"?n.role.toLowerCase():void 0;return e==="session_meta"?{type:"custom"}:s==="user"||r==="user_message"?{type:"user_prompt",role:"user"}:s==="assistant"||r==="agent_message"||r==="assistant_message"?{type:"assistant_message",role:"assistant"}:r.includes("function_call")||r.includes("tool_call")||r.includes("exec_command_begin")||r.includes("exec_command_start")?{type:"tool_call"}:r.includes("function_call_output")||r.includes("tool_result")||r.includes("exec_command_end")||r.includes("exec_command_complete")?{type:"tool_result"}:r.includes("error")?{type:"error"}:e.includes("compacted")||r.includes("compacted")?{type:"session_compact"}:{type:"custom",role:s}}function Us(t,e=0){if(!Yl(t))return{events:[],nextOffset:e,reset:!1};let n=Zl(t).size,r=e>n,s=r?0:e;if(s>=n)return{events:[],nextOffset:n,reset:r};let o=n-s,i=Buffer.alloc(o),a=Xl(t,"r");try{Ql(a,i,0,o,s)}finally{Ul(a)}let c=i.toString("utf8"),u=c.lastIndexOf(`
|
|
116
116
|
`);if(u<0)return{events:[],nextOffset:s,reset:r};let p=c.slice(0,u+1),l=0,f=[];for(let d of p.split(`
|
|
117
|
-
`)){if(!d)continue;let
|
|
118
|
-
`,"utf8"),S=s+l;l+=
|
|
117
|
+
`)){if(!d)continue;let m=Buffer.byteLength(d+`
|
|
118
|
+
`,"utf8"),S=s+l;l+=m;let g;try{g=JSON.parse(d)}catch{continue}let y=Gs(g),v=td(y);f.push({type:v.type,timestamp:ed(y),role:v.role,sourceEventId:`rollout:${S}`,sourceSequence:S,data:y,provenance:{source:"codex-rollout",sourcePath:t,sourceOffset:S}})}return{events:f,nextOffset:s+Buffer.byteLength(p,"utf8"),reset:r}}var nd=[/^<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*$/],rd=[/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],sd=["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 od(t){let e=t.toLowerCase();return sd.some(n=>e.includes(n))}function id(t){if(!t.trim())return!0;for(let e of nd)if(e.test(t))return!0;return od(t),!1}function ad(t){let e=t;for(let n of rd)e=e.replace(n,r=>{let s=r.split(/[:\s=]+/);return s.length>1?`${s[0]}: [REDACTED]`:"[REDACTED]"});return e}function gn(t){let e=t.trim();return e?id(e)?{content:"",filtered:!0,reason:"noise"}:{content:ad(e),filtered:!1}:{content:"",filtered:!0,reason:"empty"}}function Pt(t){let e={};for(let[n,r]of Object.entries(t))if(typeof r=="string"){let s=gn(r);s.filtered||(e[n]=s.content)}else r&&typeof r=="object"&&!Array.isArray(r)?e[n]=Pt(r):Array.isArray(r)?e[n]=r.map(s=>{if(typeof s=="string"){let o=gn(s);return o.filtered?null:o.content}return s&&typeof s=="object"?Pt(s):s}).filter(s=>s!==null):e[n]=r;return e}function Ys(t){let e=typeof t.type=="string"?t.type.toLowerCase():"";if(e.includes("system")||e.includes("ephemeral")||e==="tool_call"&&!t.result)return!0;if(t.data&&typeof t.data=="object"){let n=t.data,r=typeof n.content=="string"?n.content:"";if(r&&gn(r).filtered)return!0}return!1}async function _e(t){let e=t.threadId.trim();if(!e)throw new Error("Codex thread ID is required");let n=Ne(t.rolloutPath),r=t.cwd??n.cwd;if(r&&!Mt(t.project.rootPath,r))throw new Error(`Codex thread does not belong to project: ${r}`);if(n.threadId&&n.threadId!==e)throw new Error(`Codex rollout thread mismatch: expected ${e}, got ${n.threadId}`);let s=new It({project:t.project,storage:t.storage,agent:"codex",nativeSessionId:e,metadata:{source:"codex-rollout",rolloutPath:t.rolloutPath,cwd:r,client:t.client},eventContext:{source:"codex",cwd:r??t.project.rootPath,turnId:t.turnId}}),o=s.status(),i=o.sourceCursors["codex.rollout.path"],a=Number(o.sourceCursors["codex.rollout.offset"]??0);i&&i!==t.rolloutPath&&(a=0),(!Number.isFinite(a)||a<0)&&(a=0);let c=Us(t.rolloutPath,a),u=[];o.lastSequence===0&&u.push({type:"session_start",sourceEventId:`codex:${e}:start`,data:{threadId:e,cwd:r,rolloutPath:t.rolloutPath,sessionMeta:n.raw},provenance:{source:"codex-rollout",sourcePath:t.rolloutPath}}),i&&i!==t.rolloutPath&&u.push({type:"custom",sourceEventId:`codex:${e}:rollout-rotation:${t.rolloutPath}`,data:{event:"rollout_rotation",previousPath:i,rolloutPath:t.rolloutPath},provenance:{source:"codex-rollout"}}),c.reset&&u.push({type:"custom",sourceEventId:`codex:${e}:rollout-reset:${c.nextOffset}`,data:{event:"rollout_reset"},provenance:{source:"codex-rollout",sourcePath:t.rolloutPath}});let p=c.events.filter(d=>!Ys(d.data)).map(d=>({...d,data:Pt(d.data)}));if(u.push(...p),p.length>0)try{let d=Ve(t.project,"codex",e),m=p.map((y,v)=>({version:1,id:`codex-work-${e}-${y.sourceSequence??v}`,sequence:v+1,projectId:t.project.id,agent:"codex",nativeSessionId:e,type:y.type,timestamp:y.timestamp??new Date().toISOString(),role:y.role,sourceEventId:y.sourceEventId,sourceSequence:y.sourceSequence,data:y.data??{},provenance:y.provenance??{}})),S=le(d,m),g=wt(t.project,S);xt(t.project,g),Ct(t.project,{agent:"codex",nativeSessionId:e,observations:S,workState:g})}catch{}t.idle&&t.turnId&&u.push({type:"session_idle",sourceEventId:`codex:${e}:turn:${t.turnId}:idle`,data:{turnId:t.turnId,client:t.client},provenance:{source:"codex-notify"}});let l=s.recordMany(u);if(s.setSourceCursor("codex.rollout.path",t.rolloutPath),s.setSourceCursor("codex.rollout.offset",c.nextOffset),t.turnId&&s.setSourceCursor("codex.last.turn",t.turnId),t.idle&&p.length>0)try{let d=p.map(S=>JSON.stringify(S.data)),m=tt(d,e);s.setSourceCursor("codex.session.summary",m.summary),s.setSourceCursor("codex.session.facts_count",m.durableFacts.length),dr()&&!mr()&&s.setSourceCursor("codex.raw_transcript.archived","local")}catch{}let f=await s.flush();return{threadId:e,imported:l.length,rolloutEvents:c.events.length,eventCount:f.eventCount,chunkCount:f.chunkCount,status:f.status,rolloutOffset:c.nextOffset,reset:c.reset}}import{existsSync as cd}from"node:fs";import{dirname as ud,join as ld,parse as dd,resolve as pd}from"node:path";function Xs(t){let e=pd(t),n=dd(e).root;for(;;){if(cd(ld(e,".toolnet","project.json")))return new se().detect(e);if(e===n)break;let r=ud(e);if(r===e)break;e=r}return null}async function Qs(t,e,n=100){let r=[];for(let s of fn()){let o=Ne(s);if(!(!o.threadId||!o.cwd)&&Mt(t.rootPath,o.cwd)&&(r.push(await _e({project:t,storage:e,threadId:o.threadId,rolloutPath:s,cwd:o.cwd})),r.length>=n))break}return r}import{existsSync as fd,mkdirSync as Zs,readFileSync as md,writeFileSync as eo}from"node:fs";import{homedir as to}from"node:os";import{dirname as no,join as yn}from"node:path";function gd(t){let e=[],n=/"((?:\\.|[^"\\])*)"|'([^']*)'/g,r;for(;r=n.exec(t);){let s=r[1]??r[2]??"";try{e.push(r[1]!==void 0?JSON.parse(`"${s}"`):s)}catch{e.push(s)}}return e}function ro(t={}){let e=t.configFile??yn(process.env.CODEX_HOME??yn(to(),".codex"),"config.toml"),n=t.previousFile??yn(to(),".config","toolnet-memory","codex-notify-previous.json");Zs(no(e),{recursive:!0}),Zs(no(n),{recursive:!0});let r=fd(e)?md(e,"utf8"):"",s=t.binary??"toolnet-memory",o=`notify = [${JSON.stringify(s)}, "session:codex-notify"]`,i=r.split(`
|
|
119
119
|
`),a=i.findIndex(f=>/^\s*\[/.test(f));a<0&&(a=i.length);let c=-1,u=-1;for(let f=0;f<a;f+=1)if(/^\s*notify\s*=/.test(i[f])){if(c=f,u=f,i[f].includes("[")&&!i[f].includes("]"))for(;u+1<a&&(u+=1,!i[u].includes("]")););break}let p=[];if(c>=0){let f=i.slice(c,u+1).join(`
|
|
120
|
-
`);p=
|
|
120
|
+
`);p=gd(f),i.splice(c,u-c+1,o)}else a=i.findIndex(f=>/^\s*\[/.test(f)),a<0&&(a=i.length),i.splice(a,0,o);let l=p.length>=2&&p[p.length-1]==="session:codex-notify";return p.length>0&&!l&&eo(n,JSON.stringify(p,null,2)+`
|
|
121
121
|
`,{encoding:"utf8",mode:384}),r=i.join(`
|
|
122
122
|
`),r.endsWith(`
|
|
123
123
|
`)||(r+=`
|
|
124
|
-
`),
|
|
125
|
-
`,{encoding:"utf8",mode:384}),e}import{existsSync as
|
|
126
|
-
`);if(
|
|
127
|
-
`)),i=Math.max(0,e-o);if(i>=16){let a=Math.floor(i*3.2),c=
|
|
128
|
-
`).trim()}async function
|
|
124
|
+
`),eo(e,r,{encoding:"utf8",mode:384}),{configFile:e,previousFile:n,preservedPrevious:p.length>0&&!l}}import{existsSync as yd,mkdirSync as hd,readFileSync as Sd,writeFileSync as kd}from"node:fs";import{homedir as vd}from"node:os";import{dirname as wd,join as so}from"node:path";function bd(t){return`'${t.replace(/'/g,"'\\''")}'`}function oo(t={}){let e=t.hooksFile??so(process.env.CODEX_HOME??so(vd(),".codex"),"hooks.json");hd(wd(e),{recursive:!0});let n={};if(yd(e))try{n=JSON.parse(Sd(e,"utf8"))}catch(a){throw new Error(`Invalid existing Codex hooks.json: ${a instanceof Error?a.message:String(a)}`)}let r=n.hooks&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)?n.hooks:{};n.hooks=r;let o=(Array.isArray(r.SessionStart)?r.SessionStart:[]).filter(a=>{try{return!JSON.stringify(a).includes("session:codex-context")}catch{return!0}}),i=t.binary??"toolnet-memory";return o.push({matcher:"startup|resume|clear|compact",hooks:[{type:"command",command:`${bd(i)} session:codex-context`,timeout:15,additionalContextLimit:1e3,statusMessage:"Loading ToolNet project continuity"}]}),r.SessionStart=o,kd(e,JSON.stringify(n,null,2)+`
|
|
125
|
+
`,{encoding:"utf8",mode:384}),e}import{existsSync as qh,mkdirSync as Id,readFileSync as Vh,writeFileSync as Ad}from"node:fs";import{dirname as Md,join as ao}from"node:path";function hn(t){if(!t)return 0;let e=Array.from(t).length,n=t.trim().split(/\s+/u).filter(Boolean).length;return Math.ceil(Math.max(e/3.5,n*1.3))}function C(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:n.slice(0,Math.max(0,e-1)).trimEnd()+"\u2026"}function xd(t){let e=[],n=!1;for(let r of t.split(/\r?\n/u)){let s=r.trim();if(s.includes("<!--")&&(n=!0),n){s.includes("-->")&&(n=!1);continue}let o=s.toLowerCase();if(!(!s||s.startsWith("#")||s==="```"||o.startsWith("- [enforce]")||o.startsWith("* [enforce]")||o.startsWith("- [advisory]")||o.startsWith("* [advisory]"))&&(s=s.replace(/^[-*]\s+/u,""),s&&e.push(C(s,280)),e.length>=16))break}return e}function jd(t){let e=[],n=[];for(let r of t.split(/\\r?\\n/u)){let s=r.trim(),o=s.toLowerCase(),a=["- [enforce]","* [enforce]","- [advisory]","* [advisory]"].find(u=>o.startsWith(u));if(!a)continue;let c=s.slice(a.length).trim();c&&(a.includes("enforce")?e.push(c):n.push(c))}return{enforce:e,advisory:n}}function Cd(t,e){let n=[];for(let r of t){let s=[...n,r].join(`
|
|
126
|
+
`);if(hn(s)<=e){n.push(r);continue}let o=hn(n.join(`
|
|
127
|
+
`)),i=Math.max(0,e-o);if(i>=16){let a=Math.floor(i*3.2),c=C(r,a);c&&n.push(c)}break}return n.join(`
|
|
128
|
+
`).trim()}async function io(t){let e=Math.max(256,Math.min(2e3,t.maxTokens??1e3)),n=kt(t.project,!1),r=n?.content??"";r||(r=await t.storage.getText(`projects/${t.project.id}/project/manual.md`)??"");let s=jd(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?xd(r):[],c=await mt(t.project,t.storage),u=await ys(t.project,t.storage),p=await _s(t.project,t.storage),l=[];if(l.push("[TOOLNET PROJECT CONTEXT]"),l.push(`Project: ${t.project.name}`),l.push("Continue existing project state. Do not restart completed work unless evidence shows it is necessary."),r&&l.push(`Full operating manual: ${St(t.project)}`),o.length){l.push("","PROJECT RULES \u2014 MUST FOLLOW");for(let d of o.slice(0,24))l.push(`- [ENFORCE] ${C(d,240)}`)}if(i.length){l.push("","PROJECT PREFERENCES");for(let d of i.slice(0,10))l.push(`- ${C(d,220)}`)}if(u&&(u.mission&&l.push("","MISSION",C(u.mission.value,420)),u.activeObjective&&l.push("","CURRENT OBJECTIVE",C(u.activeObjective.value,420)),u.why&&l.push("","WHY THIS WORK MATTERS",C(u.why.value,420)),u.desiredOutcome&&l.push("","DESIRED OUTCOME",C(u.desiredOutcome.value,420)),u.planRationale&&l.push("","WHY THIS APPROACH",C(u.planRationale.value,420))),c){if(l.push("","ACTIVE WORK"),c.goal&&l.push(`Goal: ${C(c.goal,320)}`),c.plan&&l.push(`Plan: ${C(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: ${C(d.objective.value,340)}`),d.why?l.push(`Why this phase: ${C(d.why.value,340)}`):l.push("Why this phase: not explicitly recorded. Inspect existing implementation before assuming intent."),d.deliverable&&l.push(`Deliverable: ${C(d.deliverable.value,340)}`),d.dependencies.length&&l.push(`Depends on: ${d.dependencies.slice(0,4).map(m=>C(m.value,180)).join("; ")}`),d.acceptanceCriteria.length&&(l.push("","DEFINITION OF DONE"),d.acceptanceCriteria.slice(0,6).forEach(m=>{l.push(`- ${C(m.value,260)}`)})),d.openQuestions.length&&(l.push("","OPEN QUESTIONS FOR CURRENT PHASE"),d.openQuestions.slice(0,4).forEach(m=>{l.push(`- ${C(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}. ${C(d,260)}`)})),c.blockers.length&&(l.push("","BLOCKERS"),c.blockers.slice(0,5).forEach(d=>{l.push(`- ${C(d,260)}`)})),c.warnings.length&&(l.push("","ATTENTION"),c.warnings.slice(-5).forEach(d=>{l.push(`- ${C(d,260)}`)})),c.decisions.length&&(l.push("","RECENT DECISIONS"),c.decisions.slice(-5).forEach(d=>{l.push(`- ${C(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(`- ${C(d.value,260)}`)})),p&&l.push(`Latest handoff: ${p.reason} / ${p.sourceSession.agent}`),a.length){l.push("","OPERATING NOTES");for(let d of a)l.push(`- ${d}`)}l.push("","Before changing anything: verify the current repository state and continue from the active phase/task above.");let f=Cd(l,e);return{version:1,projectId:t.project.id,projectName:t.project.name,text:f,estimatedTokens:hn(f),maxTokens:e,hasManual:!!r,hasWorkState:!!c,hasHandoff:!!p,generatedAt:new Date().toISOString()}}function Pd(t){return ao(t.rootPath,".toolnet","context","startup.md")}function Ed(t){return ao(t.rootPath,".toolnet","context","startup.json")}function Od(t,e){let n=Pd(t);Id(Md(n),{recursive:!0}),Ad(n,e.text.endsWith(`
|
|
129
129
|
`)?e.text:e.text+`
|
|
130
|
-
`,{encoding:"utf8",mode:384}),
|
|
130
|
+
`,{encoding:"utf8",mode:384}),R(Ed(t),e)}async function co(t,e,n=800){let s=(await io({project:t,storage:e,maxTokens:n})).text;Ze(s)>n&&(s=et(s,n),s+=`
|
|
131
131
|
|
|
132
132
|
[Context trimmed by ToolNet Memory token budget]
|
|
133
|
-
`);let i={version:1,projectId:t.id,projectName:t.name,text:s,digest:
|
|
133
|
+
`);let i={version:1,projectId:t.id,projectName:t.name,text:s,digest:w(s),estimatedTokens:Ze(s),generatedAt:new Date().toISOString()};return Od(t,i),await e.put(`projects/${t.id}/context/startup.md`,i.text+`
|
|
134
134
|
`,"text/markdown"),await e.put(`projects/${t.id}/context/startup.json`,JSON.stringify(i,null,2)+`
|
|
135
|
-
`,"application/json"),i}import{existsSync as
|
|
135
|
+
`,"application/json"),i}import{existsSync as Kd,readFileSync as Fd}from"node:fs";import{join as Ld}from"node:path";import{existsSync as uo,mkdirSync as Td,readFileSync as lo,renameSync as Rd,writeFileSync as Nd}from"node:fs";import{dirname as _d,join as po}from"node:path";function fo(t){return po(t.rootPath,".toolnet","context","handoff.md")}function mo(t){return po(t.rootPath,".toolnet","context","handoff.json")}function go(t,e){Td(_d(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`;Nd(n,e.endsWith(`
|
|
136
136
|
`)?e:`${e}
|
|
137
|
-
`,{encoding:"utf8",mode:384}),
|
|
138
|
-
`)}function
|
|
139
|
-
`).trim();if(!n)return null;let r={version:1,projectId:t.id,projectName:t.name,text:n,digest:
|
|
137
|
+
`,{encoding:"utf8",mode:384}),Rd(n,t)}function $d(t,e){go(t,`${JSON.stringify(e,null,2)}
|
|
138
|
+
`)}function yo(t,e){let n=e.replace(/\r\n/g,`
|
|
139
|
+
`).trim();if(!n)return null;let r={version:1,projectId:t.id,projectName:t.name,text:n,digest:w(n),generatedAt:new Date().toISOString()};return go(fo(t),n),$d(mo(t),r),r}function ho(t){let e=fo(t);if(!uo(e))return null;try{let n=lo(e,"utf8").trim();if(!n)return null;let r=new Date(0).toISOString(),s=mo(t);if(uo(s))try{let o=JSON.parse(lo(s,"utf8"));typeof o.generatedAt=="string"&&(r=o.generatedAt)}catch{}return{version:1,projectId:t.id,projectName:t.name,text:n,digest:w(n),generatedAt:r}}catch{return null}}function Wd(t){let e=Ld(t.rootPath,".toolnet","current.md");if(!Kd(e))return null;try{return Fd(e,"utf8").trim()}catch{return null}}function Dd(t,e){let n=e.replace(/\r\n/g,`
|
|
140
140
|
`).trim(),r=2400,s=n.length>r?`${n.slice(0,r)}
|
|
141
141
|
|
|
142
|
-
[Current work truncated for fast handoff]`:n,o=
|
|
143
|
-
`)}function
|
|
142
|
+
[Current work truncated for fast handoff]`:n,o=Ls(t);return["# ToolNet Fast Handoff","",`Project: ${t.name}`,"",...o?[o,""]:[],s,"","---","","Continuation rule:","- Continue unfinished work; do not redo completed steps.","- Query ToolNet Memory only when deeper history is needed."].join(`
|
|
143
|
+
`)}function So(t){let e=Wd(t);if(e===null)return{updated:!1,reason:"missing-current",chars:0};if(!e.trim())return{updated:!1,reason:"empty-current",chars:0};let n=Dd(t,e);return ho(t)?.text.trim()===n.trim()?{updated:!1,reason:"unchanged",chars:n.length}:(yo(t,n),{updated:!0,reason:"updated",chars:n.length})}function Et(t,e){let n=t.indexOf(e);return n>=0?t[n+1]:void 0}function ko(t){let e=Ke(),n=On(Pn({provider:e.storage.provider,huggingface:e.storage.huggingface,localRoot:e.storage.localRoot}),{attempts:3});return new qe(n,t.id,t.name,t.remote??t.name)}async function Jd(t){for(let e=0;e<10;e+=1){let n=mn(t);if(n)return n;await new Promise(r=>setTimeout(r,150))}return null}function Gd(t){let e=Bd(Hd(),".config","toolnet-memory","codex-notify-previous.json");if(zd(e))try{let n=JSON.parse(qd(e,"utf8"));if(!Array.isArray(n)||n.length===0||!n.every(s=>typeof s=="string"))return;Vd(n[0],[...n.slice(1),t],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function Ud(t){let e;try{e=JSON.parse(t)}catch{return}if(e.type!=="agent-turn-complete")return;let r=typeof e["thread-id"]=="string"?e["thread-id"]:"",s=typeof e["turn-id"]=="string"?e["turn-id"]:"",o=typeof e.cwd=="string"?e.cwd:"",i=typeof e.client=="string"?e.client:void 0;if(!r||!o)return;let a=Xs(o);if(!a)return;let c=await Jd(r);if(!c)return;let u=ko(a);await _e({project:a,storage:u,threadId:r,rolloutPath:c,cwd:o,turnId:s,client:i,idle:!0});try{await co(a,u,800)}catch{}try{So(a)}catch{}}async function Yd(){let[t="help",...e]=process.argv.slice(2);if(t==="install-notify"){let o=Et(e,"--bin"),i=ro({binary:o}),a=oo({binary:o});console.log(`\u2705 Codex notify installed: ${i.configFile}`),i.preservedPrevious&&console.log(`\u2705 Previous notify preserved: ${i.previousFile}`),console.log(`\u2705 Codex SessionStart context hook: ${a}`);return}if(t==="notify"){let o=e[e.length-1]??"";try{await Ud(o)}finally{Gd(o)}return}let n=Et(e,"--project")??process.cwd(),r=new se().detect(n),s=ko(r);if(t==="sync"){let o=e[0];if(!o)throw new Error("Usage: sync <thread-id>");let i=Et(e,"--rollout")??mn(o);if(!i)throw new Error(`Codex rollout not found for ${o}`);let a=await _e({project:r,storage:s,threadId:o,rolloutPath:i,idle:e.includes("--idle")});console.log(JSON.stringify(a,null,2));return}if(t==="recover"){let o=Number(Et(e,"--limit")??100),i=await Qs(r,s,Number.isFinite(o)?o:100);console.log(JSON.stringify({project:r.name,sessions:i.length,imported:i.reduce((a,c)=>a+c.imported,0)},null,2));return}console.log(`Codex Session Adapter
|
|
144
144
|
|
|
145
145
|
Commands:
|
|
146
146
|
install-notify
|
|
147
147
|
sync <thread-id> [--project PATH]
|
|
148
148
|
recover [--project PATH] [--limit N]
|
|
149
|
-
`)}
|
|
149
|
+
`)}Yd().catch(t=>{process.argv[2]==="notify"&&process.exit(0),console.error(t instanceof Error?t.message:t),process.exit(1)});
|