context-mode 2.0.0-next.37 → 2.0.0-next.38

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/hook.mjs CHANGED
@@ -24,7 +24,7 @@ Run the command on the line above with Bash instead. It runs the same command in
24
24
  `,Nd=`
25
25
  `;function Gt(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(cc)<0?t:t.split(cc).join(Nd)}import{basename as z_,dirname as J_,join as ac,posix as $_,resolve as Q_,win32 as Z_}from"node:path";var yd=Object.freeze({NODE_TOO_OLD:"Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",NO_SQLITE:"node:sqlite failed to load. Fix: run ctx_doctor.",DB_GONE:"context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",NO_PROJECT:"Project source <kind> is missing. Fix: run ctx_doctor.",UNKNOWN_FIELD:'Unknown field "<f>". Fix: use "queries".',TIMEOUT:"Timed out after <ms> ms. Fix: pass background: true.",NO_GIT_BASH:"Git Bash not found. Fix: install Git for Windows.",NO_RUNTIME:"No <lang> runtime on PATH. Fix: install it or pick another language.",FETCH_FAILED:"Fetch failed: <code>. Fix: check the URL or proxy.",SSRF:"Blocked private address <host>. Fix: use a public URL.",OUTSIDE_ROOT:"Path <p> is outside the project. Fix: use a path inside <root>.",INVALID_ARGS:"Invalid argument <field>. Fix: <action>.",ONE_OF_INPUT:"Pass exactly one of <names>. Fix: drop the extra field.",SPAWN_FAILED:"Failed to start the process: <detail>. Fix: check the command and PATH.",DB_CORRUPT:"context.db failed integrity_check. Fix: run ctx_doctor.",SCHEMA_STALE:"context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.",NO_GIT_DIR:"No git repository at <path>. Fix: run context-mode inside a git repository.",NO_HOME:"Env var <name> is not set. Fix: set <name> to your home directory.",PLUGIN_ROOT_MISSING:"Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.",BUNDLE_HASH_MISMATCH:"Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.",CONFIG_PARSE_FAILED:"<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade."});function Id(e,t){let n=yd[e],o="",r=0;for(;r<n.length;){if(n[r]!=="<"){o+=n[r],r+=1;continue}let s=r+1;for(;s<n.length&&n[s]!=="<"&&n[s]!==">";)s+=1;if(s>=n.length){o+=n.slice(r);break}if(n[s]==="<"){o+="<",r+=1;continue}let i=n.slice(r+1,s),c=t[i];if(c===void 0)throw new Error("formatError: missing var "+i+" for "+e);o+=String(c),r=s+1}return o}var T=class extends Error{code;vars;constructor(t,n){super(Id(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{mkdirSync:Cd,realpathSync:kd}=process.getBuiltinModule("node:fs");function me(e,t=process.platform){let n=o=>o!==void 0&&o!=="";return t==="win32"?n(e.USERPROFILE)?e.USERPROFILE:n(e.HOMEDRIVE)&&n(e.HOMEPATH)?e.HOMEDRIVE+e.HOMEPATH:n(e.HOME)?e.HOME:null:n(e.HOME)?e.HOME:n(e.USERPROFILE)?e.USERPROFILE:null}function Be(e,t){let n=e[ht];return n!==void 0&&n!==""?n:ac(t,...Os["claude-code"])}function Dd(e,t=process.platform){let n=me(e,t);if(n!==null)return n;throw new T("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function lc(e){let t=ac(Dd(e),ct.slice(1));return Cd(t,{recursive:!0}),kd.native(t)}var{readFileSync:xc}=process.getBuiltinModule("node:fs");function he(e){return e.agentId!==void 0&&e.agentId!==""}function go(e,t){if(t===null)return"C";let n=re(e.agent),o=new Set(t);for(let r of ot)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function mo(e,t){if(!he(e))return null;let n=re(e.agent);if(t.manifestTools!==void 0)return fc(t.manifestTools.map(c=>_o(n,c)));let o=e.agentType??"",r=Ld(o,t);if(r===null)return null;let s=(r.tools??Hd(n)).map(c=>_o(n,c)),i=r.disallowed.map(c=>_o(n,c));return fc(s.filter(c=>!i.some(a=>vd(a,c))))}function Ld(e,t){if(!wd(e))return null;let n=Pd(t.env);if(e.indexOf(de)>=0){if(n!==null){let s=Md(Be(t.env,n),e);if(s!==null)return s}}else{let s=Eo(Bt(t.projectDir,Tr,at,e+lt));if(s!==null)return s;if(n!==null){let i=Eo(Bt(Be(t.env,n),at,e+lt));if(i!==null)return i}}let r=t.cliAgents;if(r!==void 0&&Object.prototype.hasOwnProperty.call(r,e)){let s=r[e];return{tools:Array.isArray(s.tools)?s.tools:null,disallowed:Array.isArray(s.disallowedTools)?s.disallowedTools:[]}}return null}function wd(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(de))if(t===""||t==="."||t==="..")return!1;return!0}function Pd(e){return me(e)}function Md(e,t){let n=t.indexOf(de),o=t.slice(0,n),r=t.slice(n+de.length);if(r.indexOf(de)>=0)return null;let s;try{s=JSON.parse(Gt(xc(Bt(e,hn,Rr),"utf8")))}catch{return null}let i=s?.plugins;if(i===null||typeof i!="object")return null;for(let c of Object.keys(i)){let a=c.indexOf(Ar);if((a<0?c:c.slice(0,a))!==o)continue;let l=i[c];if(Array.isArray(l))for(let u of l){let d=u?.installPath;if(typeof d!="string"||d==="")continue;let f=Eo(Bt(d,at,r+lt));if(f!==null)return f}}return null}function Eo(e){let t;try{t=xc(e,"utf8")}catch{return null}return Ud(t)}function Ud(e){let t=e.split(`
26
26
  `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Sn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Sn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=uc(o,Nr),s=uc(o,yr);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function uc(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(t+":"))continue;let r=o.slice(t.length+1).trim();if(r===""){let s=[];for(let i=n+1;i<e.length;i++){let c=e[i].trim();if(!c.startsWith("-"))break;s.push(dc(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>dc(s.trim())).filter(s=>s!=="")}return null}function dc(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function Hd(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...ot.map(n=>e.toolNamePrefix+n)]}function _o(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(Ir)?Fd(o):o}function Fd(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||Cr.indexOf(n)>=0;t+=o?n:"_"}return t}function vd(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(bn)){let n=e.slice(bn.length);if(n!==""&&n.indexOf(On)<0)return t.startsWith(e+On)}return!1}function fc(e){return[...new Set(e.filter(t=>t!==""))]}var ce="",pc=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:ce},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:ce},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:ce},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:ce},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:ce},command:{valueShorts:ce,valueLongs:[],assignments:!1,duration:!1,refuseShorts:"vV"},xargs:{valueShorts:"aEdILnPs",valueLongs:["--arg-file","--delimiter","--max-args","--max-procs","--max-chars"],assignments:!1,duration:!1,refuseShorts:ce}}),jd=["bash","sh","zsh"],Gd="c",Bd=" -c",Wd=["-o","+o","-O","+O"],Wt="-",Xd="+",ho="--",Kd="smhd",qd=".",_c=e=>e!==""&&e>="0"&&e<="9";function Yd(e){if(e===""||!_c(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(_c(n)||n===qd))return t===e.length-1&&Kd.includes(n)}return!0}function Vd(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===ho){n++;break}if(e.assignments&&Pt(o)){n++;continue}if(o.startsWith(ho)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(Wt)&&o.length>Wt.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=Wt.length;r<o.length;r++)if(e.valueShorts.includes(o.charAt(r))){r===o.length-1&&n++;break}continue}break}if(e.duration){if(n>=t.length||!Yd(t[n]))return null;n++}return n<t.length?t.slice(n):null}function zd(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(ho)){if(o.startsWith(Wt)||o.startsWith(Xd)){o.includes(Gd)&&(t=!0),Wd.includes(o)&&n++;continue}return t?o:null}}return null}function Ec(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function So(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let a=s.toLowerCase();if(jd.includes(a)){let d=zd(i),f=d!==null&&n<H?ve(d):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=Ec(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,So(p,[...r,a+Bd],n+1,o)}return}let l=Object.hasOwn(pc,a)?pc[a]:void 0,u=l===void 0?null:Vd(l,i);if(u===null)break;r.push(a),s=so(u[0]),i=u.slice(1),c=c||io(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=H))for(let a of wt(e.raw)){let l=ve(a.body);if(l.ok)for(let u of l.commands)So(Ec(u,e),[...t,a.wrapper],n+1,o)}}function gc(e){let t=[];for(let n of e)So(n,[],0,t);return t}import{isAbsolute as $d,join as bo,relative as Qd,sep as Oo}from"node:path";var{readFileSync:Jd}=process.getBuiltinModule("node:fs"),mc=".claude",Zd="settings.local.json",hc="settings.json",ef="Bash",tf="Read",Sc=":*",bc="//",Oc="~/",Tc="./",Rc="..",nf=`
27
- \r`,of=Object.freeze({tool:ef});function rf(e,t){if(t!=="claude-code")return[];let n=me(process.env),o=process.env[ht],r=o!==void 0&&o!==""?o:n===null?null:Be(process.env,n),s=[bo(e,mc,Zd),bo(e,mc,hc)];return r===null?s:[...s,bo(r,hc)]}function Ac(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sf(e){let t;try{t=Gt(Jd(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Ac(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Ac(o))return{kind:"bad"};let r=o.deny;return r===void 0?{kind:"ok",deny:[]}:!Array.isArray(r)||!r.every(s=>typeof s=="string")?{kind:"bad"}:{kind:"ok",deny:r}}function Nc(e,t){let n=[];for(let o of rf(e,t)){let r=sf(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function cf(e,t){let n=[],o=0;for(;o<e.length;){let r=e[o];if(r==="*"&&t&&e[o+1]==="*"){let s=e[o+2]==="/";n.push({t:s?"globstarDir":"globstar"}),o+=s?3:2;continue}r==="*"?(n.length===0||n[n.length-1].t!=="star")&&n.push({t:"star"}):r==="?"?n.push({t:"any1"}):n.push({t:"lit",c:r}),o++}return n}function Y(e,t,n){let o=cf(e,n),r=t.length,s=new Uint8Array(r+1);s[r]=1;for(let i=o.length-1;i>=0;i--){let c=o[i],a=new Uint8Array(r+1),l=0;for(let u=r;u>=0;u--){let d=u<r,f=d?t[u]:"";switch(c.t){case"lit":a[u]=d&&f===c.c?s[u+1]:0;break;case"any1":a[u]=d&&!(n&&f==="/")?s[u+1]:0;break;case"star":a[u]=s[u]||(d&&!(n&&f==="/")?a[u+1]:0);break;case"globstar":a[u]=s[u]||(d?a[u+1]:0);break;case"globstarDir":d&&f==="/"&&s[u+1]&&(l=1),a[u]=s[u]||l;break}}s=a}return s[0]===1}function af(e){let t=e.indexOf("(");if(t<1||!e.endsWith(")"))return null;let n=e.slice(t+1,e.length-1);return n===""?null:{tool:e.slice(0,t),glob:n}}function lf(e,t){if(!e.endsWith(Sc))return Y(e,t,!1);let n=e.slice(0,e.length-Sc.length);if(Y(n,t,!1))return!0;for(let o=0;o<t.length;o++)if(nf.includes(t[o])&&Y(n,t.slice(0,o),!1))return!0;return!1}var uf=/^[A-Za-z]:(?=\/)/;function We(e){return Oo==="/"?e:e.split(Oo).join("/")}function df(e,t,n){if(e.startsWith(Tc)){if(n===void 0)return!1;let r=Qd(n,t);return r===""||r===Rc||r.startsWith(Rc+Oo)||$d(r)?!1:Y(e.slice(Tc.length),We(r),!0)}let o=We(t);if(e.startsWith(bc)){let r=We(e.slice(bc.length-1));return Y(r,o,!0)||Y(r,o.replace(uf,""),!0)}if(e.startsWith(Oc)){let r=me(process.env);return r!==null&&Y(We(r)+e.slice(Oc.length-1),o,!0)}return Y(We(e),o,!0)}function V(e,t,n=of){for(let o of t){let r=af(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===tf?df(r.glob,e,n.projectDir):lf(r.glob,e))return o}return null}var mE=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),yc='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var ff="{size}",xf="{path}";function Xt(e,t,n=""){return k(yc,n).split(ff).join(String(t)).split(xf).join(e)}var{statSync:pf}=process.getBuiltinModule("node:fs"),Dc="Bash",Ro="Read",_f="WebFetch",Ef="ctx_execute",gf="ctx_batch",Lc="shell",mf="1",z="-",Ao="--",hf="=",Sf=".",Ic=",",To="p",bf=["-e","--expression"],Of=";&|(`\n\r",le=Object.freeze({kind:"allow"}),G=e=>({kind:"deny",reason:e}),ae=e=>typeof e=="string"?e:void 0,Cc=e=>e!=null,J=(e,t)=>e.includes(t);function wc(e,t,n){let o=e.tool;if(o===void 0)return le;let r=o.canonicalName,s=o.input,i;if(n===null){if(process.env[Or]===mf)return G(k(ut,t.toolNamePrefix));process.stderr.write(Yr+`
27
+ \r`,of=Object.freeze({tool:ef});function rf(e,t){if(t!=="claude-code")return[];let n=me(process.env),o=process.env[ht],r=o!==void 0&&o!==""?o:n===null?null:Be(process.env,n),s=[bo(e,mc,Zd),bo(e,mc,hc)];return r===null?s:[...s,bo(r,hc)]}function Ac(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sf(e){let t;try{t=Gt(Jd(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Ac(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Ac(o))return{kind:"bad"};let r=o.deny;return r===void 0?{kind:"ok",deny:[]}:!Array.isArray(r)||!r.every(s=>typeof s=="string")?{kind:"bad"}:{kind:"ok",deny:r}}function Nc(e,t){let n=[];for(let o of rf(e,t)){let r=sf(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function cf(e,t){let n=[],o=0;for(;o<e.length;){let r=e[o];if(r==="*"&&t&&e[o+1]==="*"){let s=e[o+2]==="/";n.push({t:s?"globstarDir":"globstar"}),o+=s?3:2;continue}r==="*"?(n.length===0||n[n.length-1].t!=="star")&&n.push({t:"star"}):r==="?"?n.push({t:"any1"}):n.push({t:"lit",c:r}),o++}return n}function Y(e,t,n){let o=cf(e,n),r=t.length,s=new Uint8Array(r+1);s[r]=1;for(let i=o.length-1;i>=0;i--){let c=o[i],a=new Uint8Array(r+1),l=0;for(let u=r;u>=0;u--){let d=u<r,f=d?t[u]:"";switch(c.t){case"lit":a[u]=d&&f===c.c?s[u+1]:0;break;case"any1":a[u]=d&&!(n&&f==="/")?s[u+1]:0;break;case"star":a[u]=s[u]||(d&&!(n&&f==="/")?a[u+1]:0);break;case"globstar":a[u]=s[u]||(d?a[u+1]:0);break;case"globstarDir":d&&f==="/"&&s[u+1]&&(l=1),a[u]=s[u]||l;break}}s=a}return s[0]===1}function af(e){let t=e.indexOf("(");if(t<1||!e.endsWith(")"))return null;let n=e.slice(t+1,e.length-1);return n===""?null:{tool:e.slice(0,t),glob:n}}function lf(e,t){if(!e.endsWith(Sc))return Y(e,t,!1);let n=e.slice(0,e.length-Sc.length);if(Y(n,t,!1))return!0;for(let o=0;o<t.length;o++)if(nf.includes(t[o])&&Y(n,t.slice(0,o),!1))return!0;return!1}var uf=/^[A-Za-z]:(?=\/)/;function We(e){return Oo==="/"?e:e.split(Oo).join("/")}function df(e,t,n){if(e.startsWith(Tc)){if(n===void 0)return!1;let r=Qd(n,t);return r===""||r===Rc||r.startsWith(Rc+Oo)||$d(r)?!1:Y(e.slice(Tc.length),We(r),!0)}let o=We(t);if(e.startsWith(bc)){let r=We(e.slice(bc.length-1));return Y(r,o,!0)||Y(r,o.replace(uf,""),!0)}if(e.startsWith(Oc)){let r=me(process.env);return r!==null&&Y(We(r)+e.slice(Oc.length-1),o,!0)}return Y(We(e),o,!0)}function V(e,t,n=of){for(let o of t){let r=af(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===tf?df(r.glob,e,n.projectDir):lf(r.glob,e))return o}return null}var mE=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),yc='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var ff="{size}",xf="{path}";function Xt(e,t,n=""){return k(yc,n).split(ff).join(String(t)).split(xf).join(e)}var{statSync:pf}=process.getBuiltinModule("node:fs"),Dc="Bash",Ro="Read",_f="WebFetch",Ef="ctx_execute",gf="ctx_batch",Lc="shell",mf="1",z="-",Ao="--",hf="=",Sf=".",Ic=",",To="p",bf=["-e","--expression"],Of=";&|(`\n\r",le=Object.freeze({kind:"allow"}),G=e=>({kind:"deny",reason:e}),ae=e=>typeof e=="string"?e:void 0,Cc=e=>e!=null,J=(e,t)=>e.includes(t);function wc(e,t,n){let o=e.tool;if(o===void 0)return le;let r=o.canonicalName,s=o.input,i;if(n===null){if(process.env[Or]===mf)return G(k(ut,t.toolNamePrefix));process.stderr.write(Yr+`
28
28
  `),i=[]}else i=n;let c=Tf(r,s,e.cwd,i);return c!==null?G(Ne+c):r===_f?yf(s,t):r===Dc?If(e,t,s,i):r===Ro?Pf(e,t,s):le}function Pc(e,t,n,o){let r=e==="webfetch",s=r?Ur.map(c=>n.toolNamePrefix+c).join(qr):n.toolNamePrefix+Mr,i=JSON.stringify(r?{url:t}:{language:Lc,code:t,intent:o??Pr});return[Tn+kr[e]+Dr,Lr,wr+s,i].join(`
29
29
  `)}function Mc(e){for(let t of xt){let n=ae(e[t]);if(n!==void 0&&n!=="")return n}}function Tf(e,t,n,o){if(o.length===0)return null;let r=s=>V(qt(n,s),o,{tool:Ro,projectDir:n});if(e===Dc){let s=ae(t.command);return s===void 0?null:V(s,o)}if(e===Ro){let s=Mc(t);return s===void 0?null:r(s)}if(e===Ef){let s=ae(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=ae(t.code);return t.language===Lc&&c!==void 0?V(c,o):null}if(e===gf&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?V(s,o):null;if(i!==null)return i}return null}function Rf(e,t){return t.length===0?null:V([e.argv0,...e.args].join(" "),t)??V(e.raw,t)}function Af(e,t){if(t.length===0)return!1;for(let n=0;n<=e.length;n++)if(!(n>0&&!Of.includes(e.charAt(n-1)))&&V(e.slice(n).trimStart(),t)!==null)return!0;return!1}function Nf(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return Vr.some(n=>t===n||t.endsWith(Sf+n))}function yf(e,t){let n=ae(e.url)??"";return Nf(n)?le:G(Pc("webfetch",n,t))}function If(e,t,n,o){let r=ae(n.command)??"",s=ve(r);if(!s.ok)return Af(r,o)?G(k(dt,t.toolNamePrefix)):kc(r,e.cwd,t)??le;let i=gc(s.commands);for(let c of i){let a=Rf(c,o);if(a!==null)return G(Ne+a)}if(!Le(t)||he(e))for(let c of i){let a=Cf(c);if(a!==null)return G(Pc(a,r,t,ae(n.description)))}return Mf(i,e.cwd,t)??kc(r,e.cwd,t)??le}function Cf(e){let t=e.argv0.toLowerCase();return J(zr,t)&&kf(t,e)?"curl":Lf(e.raw)?"http":J(Zr,t)?"build":null}function kf(e,t){return t.redirectsToFile?!Df(e,t.args):!t.endsInBoundedSink}function Df(e,t){let n=Jr[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===Ao)break;if(J($r,s)||s===Qr&&t[r+1]===z)return!1;(s===n.long||s.startsWith(z)&&!s.startsWith(Ao)&&s.includes(n.short,z.length))&&(o=!0)}return o}function Lf(e){let t=e.toLowerCase();for(let n of ns)if(t.includes(n))return!0;for(let n=t.indexOf(Ie);n>=0;n=t.indexOf(Ie,n+1)){let o=t.charAt(n+Ie.length);if(o!==""&&es.includes(o)&&t.startsWith(ts,n+Ie.length+o.length))return!0}return!1}var wf="cd";function No(e){try{let t=pf(e);return t.isFile()?t.size:-1}catch{return-1}}function Pf(e,t,n){if(!Cc(n.offset)&&!Cc(n.limit)){let o=Mc(n);if(o!==void 0){let r=qt(e.cwd,o),s=No(r);if(s>K)return G(Xt(r,s,t.toolNamePrefix))}}return le}function Mf(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&Vn(n))return null;let o=t,r=null;for(let s of e){let i=s.argv0.toLowerCase();if(i===wf&&s.args.length===1&&s.insideConstruct===void 0&&(o=qt(o,s.args[0])),s.redirectsToFile||s.endsInBoundedSink||s.pipesOut===!0||s.insideConstruct!==void 0||!J(os,i))continue;let c=Ff(i,s.args);if(c===null)continue;if(c.bounded){r=le;continue}let a=qt(o,c.file),l=No(a);if(l>K)return G(Xt(a,l,n.toolNamePrefix))}return r}function kc(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&Vn(n))return null;for(let o of ic(e,t)){let r=No(o);if(r>K)return G(Xt(o,r,n.toolNamePrefix))}return null}var Kt=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function Uf(e){if(J(An,e))return 1;for(let t of An)if(t.startsWith(Ao)?e.startsWith(t+hf):e.startsWith(t))return 0;return e.startsWith(z)&&Kt(e.slice(z.length))?0:-1}function Hf(e){if(e===To)return"all";if(!e.endsWith(To))return null;let t=e.slice(0,e.length-To.length),n=t.indexOf(Ic);return(n<0?Kt(t):Kt(t.slice(0,n))&&Kt(t.slice(n+Ic.length)))?"range":null}function Ff(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(J(rs,e)){let a=Uf(c);if(a>=0){o=!0,i+=a;continue}}if(e===ft&&J(ss,c)){r=!0;continue}if(e===ft&&J(bf,c)){s=t[i+1],i++;continue}c.startsWith(z)&&c!==z||n.push(c)}if(e===ft){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:Hf(s);if(i===null)return null;o=i==="range"}return e===is&&n.shift()!==D.identity?null:n.length===1&&n[0]!==z?{file:n[0],bounded:o}:null}import{basename as Yf,dirname as Vt,join as Ke,resolve as jc}from"node:path";import{dirname as Uc,sep as jf}from"node:path";var{realpathSync:vf}=process.getBuiltinModule("node:fs");function Gf(e){try{return vf.native(e)}catch{return}}function Yt(e){return e.split(jf).filter(t=>t!=="")}function Hc(e){let t=e.map(Gf).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=Yt(n).length;for(let s of t){let i=Yt(s),c=Yt(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;Yt(r).length>o&&Uc(r)!==r;)r=Uc(r);return r}var Bf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Wf=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],w=(e,t)=>e>>>t|e<<32-t;function Fc(e){let t=Buffer.from(e,"utf8"),n=t.length*8,o=Math.ceil((t.length+9)/64)*64,r=Buffer.alloc(o);t.copy(r),r[t.length]=128,r.writeUInt32BE(Math.floor(n/4294967296),o-8),r.writeUInt32BE(n>>>0,o-4);let s=Wf.slice(),i=new Uint32Array(64);for(let c=0;c<o;c+=64){for(let E=0;E<16;E++)i[E]=r.readUInt32BE(c+E*4);for(let E=16;E<64;E++){let h=w(i[E-15],7)^w(i[E-15],18)^i[E-15]>>>3,S=w(i[E-2],17)^w(i[E-2],19)^i[E-2]>>>10;i[E]=i[E-16]+h+i[E-7]+S>>>0}let[a,l,u,d,f,x,p,g]=s;for(let E=0;E<64;E++){let h=g+(w(f,6)^w(f,11)^w(f,25))+(f&x^~f&p)+Bf[E]+i[E]>>>0,S=(w(a,2)^w(a,13)^w(a,22))+(a&l^a&u^l&u)>>>0;g=p,p=x,x=f,f=d+h>>>0,d=u,u=l,l=a,a=h+S>>>0}s[0]=s[0]+a>>>0,s[1]=s[1]+l>>>0,s[2]=s[2]+u>>>0,s[3]=s[3]+d>>>0,s[4]=s[4]+f>>>0,s[5]=s[5]+x>>>0,s[6]=s[6]+p>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:Xf,readFileSync:Kf,realpathSync:vc,statSync:qf}=process.getBuiltinModule("node:fs");function Vf(e){switch(e){case"claude-code":return"env:CLAUDE_PROJECT_DIR";case"codex":case"copilot-cli":case"kiro":return"arg:--agent+cwd";case"vscode":return"arg:workspaceFolder";case"gemini":case"qwen":case"zcode":case"opencode":return"spawn-cwd";case"pi":return"pi:ctx.cwd"}}function Xe(e){return e===void 0||e===""?void 0:e}function zf(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return Xe(t.env.CLAUDE_PROJECT_DIR)??Xe(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return Xe(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(it);return n<0?void 0:Xe(t.argv[n+1])}case"pi:ctx.cwd":return Xe(t.piCwd)}}function Jf(e){let t;try{t=vc.native(e)}catch{throw new T("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=$f(Ke(t,En));if(o!==null){let s=Gc(Ke(o,hr));return{commonDir:vc.native(s===null?o:jc(o,s)),worktree:t,start:n}}let r=Vt(t);if(r===t)return{commonDir:null,start:n};t=r}}function $f(e){let t;try{if(qf(e).isDirectory())t=e;else{let n=Gc(e);if(n===null||!n.startsWith(mn))return null;t=jc(Vt(e),n.slice(mn.length))}}catch{return null}return Xf(Ke(t,Sr))?t:null}function Gc(e){let t;try{t=Kf(e,"utf8")}catch{return null}let n=t.indexOf(`
30
30
  `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function Qf(e,t){let{spawnSync:n}=process.getBuiltinModule("node:child_process"),o=n("git",t,{cwd:e,shell:!1,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});if(o.error!==void 0||o.status!==0)throw new T("NO_GIT_DIR",{path:e});return o.stdout.split(`
@@ -425,7 +425,7 @@ var DECISION_OPTION_KEY = "option";
425
425
  var DECISION_LABEL_JOIN = " | ";
426
426
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
427
427
  var RELEASE_BRANCH = "release";
428
- var BUNDLE_SHA = true ? "2ed67370714045804b7620af1f3af2c9eabc1713" : void 0;
428
+ var BUNDLE_SHA = true ? "ede83923546ab97898750ef7cebe34cf82e9534c" : void 0;
429
429
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
430
430
  var DOCTOR_LABEL = Object.freeze({
431
431
  D1: "version",
@@ -3747,7 +3747,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
3747
3747
  ctx_execute: 'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',
3748
3748
  ctx_batch: 'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',
3749
3749
  ctx_index: 'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',
3750
- ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',
3750
+ ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',
3751
3751
  ctx_resume: "Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",
3752
3752
  ctx_stats: "Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",
3753
3753
  ctx_doctor: "Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",
@@ -20222,17 +20222,29 @@ function runProcess(argv, o) {
20222
20222
  }
20223
20223
 
20224
20224
  // src/core/index/auto-memory.ts
20225
- import { readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
20225
+ import { readdirSync, readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
20226
20226
  import { join as join7 } from "node:path";
20227
- var CLAUDE_CODE_MEMORY_FILES = Object.freeze([
20227
+ var MEMORY_FILES = Object.freeze([
20228
20228
  Object.freeze(["CLAUDE.md"]),
20229
20229
  Object.freeze(["CLAUDE.local.md"]),
20230
- Object.freeze([".claude", "CLAUDE.md"])
20230
+ Object.freeze([".claude", "CLAUDE.md"]),
20231
+ Object.freeze(["AGENTS.md"]),
20232
+ Object.freeze(["GEMINI.md"]),
20233
+ Object.freeze(["QWEN.md"]),
20234
+ Object.freeze([".github", "copilot-instructions.md"])
20231
20235
  ]);
20236
+ var KIRO_STEERING = Object.freeze([".kiro", "steering"]);
20237
+ var MD = ".md";
20238
+ function steeringFiles(worktree) {
20239
+ try {
20240
+ return readdirSync(join7(worktree, ...KIRO_STEERING)).filter((n) => n.endsWith(MD)).sort().map((n) => [...KIRO_STEERING, n]);
20241
+ } catch {
20242
+ return [];
20243
+ }
20244
+ }
20232
20245
  function readAutoMemory(project) {
20233
- if (project.agent !== "claude-code") return [];
20234
20246
  const rows = [];
20235
- for (const segs of CLAUDE_CODE_MEMORY_FILES) {
20247
+ for (const segs of [...MEMORY_FILES, ...steeringFiles(project.worktree)]) {
20236
20248
  const path7 = join7(project.worktree, ...segs);
20237
20249
  if (!isInside(project.worktree, path7)) continue;
20238
20250
  try {
@@ -20252,6 +20264,20 @@ function readAutoMemory(project) {
20252
20264
  }
20253
20265
  return rows;
20254
20266
  }
20267
+ function memoryChunks(rows) {
20268
+ const out = [];
20269
+ rows.forEach((r, i) => {
20270
+ for (const c of chunkText(r.text, "md")) out.push({ fileNo: i + 1, label: r.label, ord: c.ord, text: c.text });
20271
+ });
20272
+ return out;
20273
+ }
20274
+ function memoryHits(chunks, q, limit) {
20275
+ if (chunks.length === 0) return [];
20276
+ const texts = chunks.map((c) => c.text);
20277
+ const any2 = rankTexts(texts, q, "any");
20278
+ const all = rankTexts(texts, q, "all");
20279
+ return chunks.map((c, i) => ({ c, s: any2[i], full: all[i] > 0 })).filter((e) => e.s > 0).sort((a, b) => Number(b.full) - Number(a.full) || b.s - a.s || a.c.fileNo - b.c.fileNo || a.c.ord - b.c.ord).slice(0, limit).map((e) => ({ sourceId: -e.c.fileNo, label: "memory " + e.c.label, ord: e.c.ord, snippet: highlight(e.c.text, q, SNIPPET_MAX_BYTES), score: e.s, full: e.full }));
20280
+ }
20255
20281
 
20256
20282
  // src/core/tools/search.ts
20257
20283
  function unknownField(issue2) {
@@ -20389,11 +20415,37 @@ function replyHits(hits, size) {
20389
20415
  while (n < size && n < hits.length && hits[n].full === true) n++;
20390
20416
  return n;
20391
20417
  }
20418
+ var MEMORY_HITS = 2;
20419
+ function mergeMemory(content, memory) {
20420
+ const out = [];
20421
+ let c = 0;
20422
+ let m = 0;
20423
+ let lastMem = true;
20424
+ while (c < content.length || m < memory.length) {
20425
+ const rank = (h) => h === void 0 ? -1 : h.full === true ? 1 : 0;
20426
+ const rc = rank(content[c]);
20427
+ const rm = rank(memory[m]);
20428
+ const mem = rc < 0 || rm > rc || rm === rc && !lastMem;
20429
+ if (mem) {
20430
+ out.push(memory[m++]);
20431
+ lastMem = true;
20432
+ } else {
20433
+ out.push(content[c++]);
20434
+ lastMem = false;
20435
+ }
20436
+ }
20437
+ return out;
20438
+ }
20439
+ var contentIn = (hits, n) => hits.slice(0, n).filter((h) => h.sourceId > 0).length;
20392
20440
  function relevance(db, given, scope, ctx, nm) {
20393
20441
  const input = { ...given, queries: decisionQueries(given) };
20394
20442
  const offset = input.offset ?? 0;
20395
20443
  const size = pageSize(input);
20396
- const fetched = input.queries.map((q) => page(db, q, input, scope, ctx, offset, 1));
20444
+ const mem = offset === 0 && scope !== "session" && input.source === void 0 ? memoryChunks(readAutoMemory(ctx.project)) : [];
20445
+ const fetched = input.queries.map((q) => {
20446
+ const content = page(db, q, input, scope, ctx, offset, 1);
20447
+ return mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, q, MEMORY_HITS));
20448
+ });
20397
20449
  const take = fetched.map((h) => replyHits(h, size));
20398
20450
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
20399
20451
  if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, offset);
@@ -20429,13 +20481,13 @@ function relevance(db, given, scope, ctx, nm) {
20429
20481
  }
20430
20482
  const line = shownLabel(hit.label, hit.sourceId) + " #" + hit.ord + ": " + hit.snippet;
20431
20483
  if (used + bytes2(line) + 1 + reserve > OUTPUT_CAP) {
20432
- cut = offset + i;
20484
+ cut = offset + contentIn(hits, i);
20433
20485
  stopped = true;
20434
20486
  break;
20435
20487
  }
20436
20488
  const room = total.get(hit.sourceId);
20437
20489
  if (room !== void 0 && mine.has(hit.sourceId) && (spent.get(hit.sourceId) ?? 0) + bytes2(line) + 1 > room * SMALL_SOURCE_SHARE * (qi + 1) / input.queries.length) {
20438
- cut = offset + i;
20490
+ cut = offset + contentIn(hits, i);
20439
20491
  break;
20440
20492
  }
20441
20493
  lines.push(line);
@@ -20450,7 +20502,7 @@ function relevance(db, given, scope, ctx, nm) {
20450
20502
  used += bytes2(line) + 1;
20451
20503
  }
20452
20504
  if (cut >= 0) more.push({ q, pos: cut });
20453
- else if (fetched[qi].length > take[qi]) more.push({ q, pos: offset + take[qi] });
20505
+ else if (contentIn(fetched[qi], fetched[qi].length) > contentIn(fetched[qi], take[qi])) more.push({ q, pos: offset + contentIn(fetched[qi], take[qi]) });
20454
20506
  });
20455
20507
  const moreLines = [];
20456
20508
  const byPos = /* @__PURE__ */ new Map();
@@ -20751,15 +20803,15 @@ var ctxBatch = Object.freeze({
20751
20803
  });
20752
20804
 
20753
20805
  // src/core/tools/doctor.ts
20754
- import { readdirSync as readdirSync5, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20806
+ import { readdirSync as readdirSync6, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20755
20807
  import { basename as basename5, dirname as dirname8, join as join16 } from "node:path";
20756
20808
 
20757
20809
  // src/core/ops/doctor-config.ts
20758
- import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
20810
+ import { existsSync as existsSync6, readdirSync as readdirSync4 } from "node:fs";
20759
20811
  import { join as join11 } from "node:path";
20760
20812
 
20761
20813
  // src/core/ops/detect-v1.ts
20762
- import { existsSync as existsSync4, opendirSync, readdirSync, readFileSync as readFileSync7 } from "node:fs";
20814
+ import { existsSync as existsSync4, opendirSync, readdirSync as readdirSync2, readFileSync as readFileSync7 } from "node:fs";
20763
20815
  import { tmpdir } from "node:os";
20764
20816
  import { join as join9 } from "node:path";
20765
20817
 
@@ -23479,7 +23531,7 @@ function scanVscode(agentHome, project, out) {
23479
23531
  }
23480
23532
  function jsonFiles(dir) {
23481
23533
  try {
23482
- return readdirSync(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
23534
+ return readdirSync2(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
23483
23535
  } catch {
23484
23536
  return [];
23485
23537
  }
@@ -23605,7 +23657,7 @@ function detectV1(agent, home, scope = {}) {
23605
23657
  }
23606
23658
 
23607
23659
  // src/core/ops/plugin-root.ts
23608
- import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23660
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23609
23661
  import { dirname as dirname6, isAbsolute as isAbsolute2, join as join10, sep as sep3 } from "node:path";
23610
23662
  import { fileURLToPath } from "node:url";
23611
23663
  function missing(agent, path7) {
@@ -23705,7 +23757,7 @@ function marketplaceRoot(adapter, env, worktree) {
23705
23757
  if (ownReal !== null && cacheReal !== null && ownReal.startsWith(cacheReal + sep3) && existsSync5(join10(ownReal, SERVER_ENTRY_FILE))) return ownReal;
23706
23758
  const pattern = join10(cache, "*", PLUGIN_NAME);
23707
23759
  if (!existsSync5(cache)) throw missing(adapter.id, pattern);
23708
- const found = readdirSync2(cache).sort().map((marketplace) => join10(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync5(dir));
23760
+ const found = readdirSync3(cache).sort().map((marketplace) => join10(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync5(dir));
23709
23761
  if (found.length !== 1) throw missing(adapter.id, found.length === 0 ? pattern : found.join(", "));
23710
23762
  return found[0];
23711
23763
  }
@@ -23848,10 +23900,10 @@ function codexNativeDir(env, home) {
23848
23900
  const cache = join11(codexDir, "plugins", PLUGIN_CACHE_DIR_NAME);
23849
23901
  if (!existsSync6(cache)) return null;
23850
23902
  const found = [];
23851
- for (const market of readdirSync3(cache)) {
23903
+ for (const market of readdirSync4(cache)) {
23852
23904
  const plugin = join11(cache, market, SERVER_KEY);
23853
23905
  if (!existsSync6(plugin)) continue;
23854
- for (const version2 of readdirSync3(plugin).sort()) {
23906
+ for (const version2 of readdirSync4(plugin).sort()) {
23855
23907
  const dir = join11(plugin, version2, CODEX_PLUGIN_SUBDIR);
23856
23908
  if (existsSync6(join11(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
23857
23909
  }
@@ -24626,7 +24678,7 @@ import { existsSync as existsSync11, mkdirSync as mkdirSync5, rmSync as rmSync3
24626
24678
  import { basename as basename4, dirname as dirname7, join as join14 } from "node:path";
24627
24679
 
24628
24680
  // src/core/store/owners.ts
24629
- import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24681
+ import { mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24630
24682
  import { basename as basename3, join as join13 } from "node:path";
24631
24683
  function ownersDir(configDir, projectKey) {
24632
24684
  return join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
@@ -24649,7 +24701,7 @@ function listLiveOwners(configDir, projectKey) {
24649
24701
  const dir = ownersDir(configDir, projectKey);
24650
24702
  let names;
24651
24703
  try {
24652
- names = readdirSync4(dir);
24704
+ names = readdirSync5(dir);
24653
24705
  } catch (err) {
24654
24706
  if (errCode2(err) === "ENOENT") return [];
24655
24707
  throw err;
@@ -25047,7 +25099,7 @@ async function hookRow(ctx, adapter, host) {
25047
25099
  function ownServerId(configDir, projectKey) {
25048
25100
  const dir = join16(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
25049
25101
  if (!existsSync13(dir)) return "";
25050
- for (const name of readdirSync5(dir)) {
25102
+ for (const name of readdirSync6(dir)) {
25051
25103
  if (!name.endsWith(OWNER_PID_EXT)) continue;
25052
25104
  if (readFileSync13(join16(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
25053
25105
  }
@@ -25351,7 +25403,7 @@ import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as
25351
25403
  import { dirname as dirname10, extname, join as join19, relative as relative3, resolve as resolve7 } from "node:path";
25352
25404
 
25353
25405
  // src/core/index/walk.ts
25354
- import { readdirSync as readdirSync6, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync7 } from "node:fs";
25406
+ import { readdirSync as readdirSync7, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync7 } from "node:fs";
25355
25407
  import { join as join18 } from "node:path";
25356
25408
  var GITIGNORE = ".gitignore";
25357
25409
  var GIT_DIR = ".git";
@@ -25366,7 +25418,7 @@ function walkDir(root, containmentRoot) {
25366
25418
  function visit(abs, rel, parent, contain, seen, found) {
25367
25419
  let entries;
25368
25420
  try {
25369
- entries = readdirSync6(abs, { withFileTypes: true });
25421
+ entries = readdirSync7(abs, { withFileTypes: true });
25370
25422
  } catch {
25371
25423
  return;
25372
25424
  }
@@ -30125,7 +30177,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
30125
30177
  }
30126
30178
 
30127
30179
  // src/core/ops/plugin-swap.ts
30128
- import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
30180
+ import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync8, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
30129
30181
  import { basename as basename6, join as join21, win32 as win322 } from "node:path";
30130
30182
  function linkTarget(path7, win) {
30131
30183
  if (!isLink(path7)) return null;
@@ -30136,7 +30188,7 @@ function isLink(path7) {
30136
30188
  return lstatSync(path7, { throwIfNoEntry: false })?.isSymbolicLink() === true;
30137
30189
  }
30138
30190
  function generations(agentDir) {
30139
- return readdirSync7(agentDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).filter((name) => !name.startsWith(UPGRADE_FETCH_DIR_PREFIX) && !name.endsWith(UPGRADE_TRASH_SUFFIX)).sort();
30191
+ return readdirSync8(agentDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).filter((name) => !name.startsWith(UPGRADE_FETCH_DIR_PREFIX) && !name.endsWith(UPGRADE_TRASH_SUFFIX)).sort();
30140
30192
  }
30141
30193
  function settleLinks(link, tmp, old, opts) {
30142
30194
  if (isLink(tmp)) unlinkSync2(tmp);
@@ -30205,7 +30257,7 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
30205
30257
  }
30206
30258
 
30207
30259
  // src/core/ops/uninstall.ts
30208
- import { existsSync as existsSync19, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
30260
+ import { existsSync as existsSync19, readdirSync as readdirSync9, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
30209
30261
  import { join as join23 } from "node:path";
30210
30262
  function row2(area, before, after) {
30211
30263
  return { area, before, after };
@@ -30321,7 +30373,7 @@ function removeProjectData(configDir, projectKey) {
30321
30373
  const dir = join23(projects, projectKey);
30322
30374
  if (!existsSync19(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
30323
30375
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
30324
- for (const name of readdirSync8(dir)) {
30376
+ for (const name of readdirSync9(dir)) {
30325
30377
  if (name !== OWNERS_DIR_NAME) rmSync7(join23(dir, name), { recursive: true, force: true });
30326
30378
  }
30327
30379
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
@@ -30466,7 +30518,7 @@ function removeV1(agent, findings) {
30466
30518
 
30467
30519
  // src/core/ops/verify-sums.ts
30468
30520
  import { createHash as createHash2 } from "node:crypto";
30469
- import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "node:fs";
30521
+ import { lstatSync as lstatSync2, readdirSync as readdirSync10, readFileSync as readFileSync17 } from "node:fs";
30470
30522
  import { join as join24 } from "node:path";
30471
30523
  function mismatch() {
30472
30524
  return new CtxError("BUNDLE_HASH_MISMATCH");
@@ -30485,7 +30537,7 @@ function parseSums(text) {
30485
30537
  return sums;
30486
30538
  }
30487
30539
  function walk3(dir, prefix, out) {
30488
- for (const entry of readdirSync9(dir, { withFileTypes: true })) {
30540
+ for (const entry of readdirSync10(dir, { withFileTypes: true })) {
30489
30541
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
30490
30542
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
30491
30543
  const abs = join24(dir, entry.name);
package/package.json CHANGED
@@ -69,5 +69,5 @@
69
69
  "url": "git+https://github.com/mksglu/context-mode.git"
70
70
  },
71
71
  "type": "module",
72
- "version": "2.0.0-next.37"
72
+ "version": "2.0.0-next.38"
73
73
  }