@misterhuydo/cairn-mcp 1.28.2 → 1.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cairn-cli.js +64 -68
  2. package/package.json +1 -1
package/dist/cairn-cli.js CHANGED
@@ -1,37 +1,37 @@
1
1
  #!/usr/bin/env node
2
- import y from"fs";import Z from"os";import S from"path";import{execSync as rs}from"child_process";import ps from"fast-glob";var Fe={".java":"java",".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".vue":"vue",".py":"python",".sql":"sql",".yml":"config",".yaml":"config",".properties":"config",".env":"config",".xml":"xml",".html":"html",".md":"markdown"};function re(e,t,n={}){let{noComments:s=!0,noEmptyLines:o=!0,aggressive:r=!1}=n,a=e;return s&&(a=Ot(a,t)),o&&(a=jt(a)),a=Tt(a),r&&(a=Pt(a)),a.trim()}function Ot(e,t){switch(t){case"java":case"typescript":case"javascript":case"vue":return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(["'`])(?:(?!\1)[^\\]|\\.)*\1|\/(?![/*])(?:[^/\\\n]|\\.)*\/[gimsuy]*|\/\/[^\n]*/g,(n,s)=>s||!n.startsWith("//")?n:"");case"python":return e.replace(/#.*$/gm,"").replace(/'''[\s\S]*?'''/g,"").replace(/"""[\s\S]*?"""/g,"");case"sql":return e.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");case"xml":case"html":return e.replace(/<!--[\s\S]*?-->/g,"");case"config":return e.replace(/#.*$/gm,"");default:return e}}function jt(e){return e.split(`
2
+ import y from"fs";import Z from"os";import x from"path";import{execSync as rs}from"child_process";import ds from"fast-glob";var Fe={".java":"java",".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".vue":"vue",".py":"python",".sql":"sql",".yml":"config",".yaml":"config",".properties":"config",".env":"config",".xml":"xml",".html":"html",".md":"markdown"};function ce(e,t,n={}){let{noComments:s=!0,noEmptyLines:o=!0,aggressive:r=!1}=n,a=e;return s&&(a=Ot(a,t)),o&&(a=Tt(a)),a=jt(a),r&&(a=Pt(a)),a.trim()}function Ot(e,t){switch(t){case"java":case"typescript":case"javascript":case"vue":return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(["'`])(?:(?!\1)[^\\]|\\.)*\1|\/(?![/*])(?:[^/\\\n]|\\.)*\/[gimsuy]*|\/\/[^\n]*/g,(n,s)=>s||!n.startsWith("//")?n:"");case"python":return e.replace(/#.*$/gm,"").replace(/'''[\s\S]*?'''/g,"").replace(/"""[\s\S]*?"""/g,"");case"sql":return e.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");case"xml":case"html":return e.replace(/<!--[\s\S]*?-->/g,"");case"config":return e.replace(/#.*$/gm,"");default:return e}}function Tt(e){return e.split(`
3
3
  `).filter(t=>t.trim().length>0).join(`
4
- `)}function Tt(e){return e.split(`
4
+ `)}function jt(e){return e.split(`
5
5
  `).map(t=>t.trimEnd()).join(`
6
- `)}function Pt(e){return e.replace(/\s+/g," ").replace(/\s*([=+\-*/%<>!&|^~?:;,{}()[\]])\s*/g,"$1").replace(/;\s*}/g,"}").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim()}function Le(e,t={}){let{noStyle:n=!1,noComments:s=!0,noEmptyLines:o=!0,aggressive:r=!1}=t,a=[],l=e.match(/<template>([\s\S]*?)<\/template>/i);if(l){let i=l[1];s&&(i=i.replace(/<!--[\s\S]*?-->/g,"")),o&&(i=i.split(`
7
- `).filter(c=>c.trim()).join(`
8
- `)),i=i.replace(/\s+/g," ").trim(),i&&a.push(`<template>${i}</template>`)}let u=e.match(/<script([^>]*)>([\s\S]*?)<\/script>/i);if(u){let i=u[1],c=re(u[2],"javascript",{noComments:s,noEmptyLines:o,aggressive:r}),p=/setup/i.test(i)?"<script setup>":"<script>";c&&a.push(`${p}${c}</script>`)}if(!n){let i=e.match(/<style([^>]*)>([\s\S]*?)<\/style>/i);if(i){let c=i[2].replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();c&&a.push(`<style${i[1]}>${c}</style>`)}}return a.join(`
6
+ `)}function Pt(e){return e.replace(/\s+/g," ").replace(/\s*([=+\-*/%<>!&|^~?:;,{}()[\]])\s*/g,"$1").replace(/;\s*}/g,"}").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim()}function Le(e,t={}){let{noStyle:n=!1,noComments:s=!0,noEmptyLines:o=!0,aggressive:r=!1}=t,a=[],c=e.match(/<template>([\s\S]*?)<\/template>/i);if(c){let i=c[1];s&&(i=i.replace(/<!--[\s\S]*?-->/g,"")),o&&(i=i.split(`
7
+ `).filter(l=>l.trim()).join(`
8
+ `)),i=i.replace(/\s+/g," ").trim(),i&&a.push(`<template>${i}</template>`)}let u=e.match(/<script([^>]*)>([\s\S]*?)<\/script>/i);if(u){let i=u[1],l=ce(u[2],"javascript",{noComments:s,noEmptyLines:o,aggressive:r}),d=/setup/i.test(i)?"<script setup>":"<script>";l&&a.push(`${d}${l}</script>`)}if(!n){let i=e.match(/<style([^>]*)>([\s\S]*?)<\/style>/i);if(i){let l=i[2].replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();l&&a.push(`<style${i[1]}>${l}</style>`)}}return a.join(`
9
9
 
10
- `)}import I from"fs";import Q from"path";import M from"fs";import Nt from"os";import C from"path";var fe=null;function z(){return fe||process.cwd()}function Ce(e){let t=fe;return fe=e,t}function G(){let e=C.join(z(),".cairn");M.mkdirSync(C.join(e,"bundles"),{recursive:!0});let t=C.join(e,".cairn-project");return M.existsSync(t)||M.writeFileSync(t,"","utf8"),e}function me(e){return e.replace(/[:/\\]/g,"-").replace(/^-+/,"")}function he(){let e=C.join(Nt.homedir(),".claude","projects",me(z()));return M.existsSync(e)?C.join(e,"memory"):null}function De(e){let t=C.join(e,"MEMORY.md");M.existsSync(t)||M.writeFileSync(t,`# Memory Index
11
- `,"utf8")}function ye(){let e=C.join(G(),"memory");M.mkdirSync(e,{recursive:!0}),De(e);let t=he();if(!t)return e;M.mkdirSync(t,{recursive:!0}),De(t);let n=s=>M.readdirSync(s).some(o=>o.endsWith(".md")&&o!=="MEMORY.md");if(!n(t)&&n(e))for(let s of M.readdirSync(e)){let o=C.join(e,s);try{if(!M.statSync(o).isFile())continue;let r=M.statSync(o);M.copyFileSync(o,C.join(t,s));try{M.utimesSync(C.join(t,s),r.atime,r.mtime)}catch{}}catch{}}return t}import J from"fs";import _e from"path";import{execSync as Mt}from"child_process";var O="would_be_lost";var Ie=2*1024*1024,ie=[2e5,1e6],We=.9;function Ue(e){for(let t of ie)if(e<=t*.98)return t;return ie[ie.length-1]}var ks=ie[0]*We,At=[256*1024,1024*1024],He=".handoff-hint",Ft=220;function ge(e,t=Ft){let n=String(e).replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Lt(e,t){try{let n=Mt(`git log --oneline --after="${t}"`,{cwd:e,encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n?n.split(`
12
- `).length:0}catch{return null}}function se(e,t){let n=typeof t?.[O]=="string"?t[O].trim():"";if(!n)return{recorded:!1,text:"",at:null,commits:null,stale:!1};let s=t[`${O}_at`]||t.checkpoint_at||null,o=s?Lt(e,s):null;return{recorded:!0,text:n,at:s,commits:o,stale:(o??0)>0}}function Se(e){if(!e.recorded)return"No handoff recorded \u2014 nothing was written down about what the last session would lose.";let t=e.stale?` (written before the ${e.commits} commit(s) since \u2014 may be stale)`:"";return`Carried forward: ${ge(e.text)}${t}`}function Dt(e=0){let t=Number(process.env.CAIRN_CONTEXT_HINT_TOKENS);return Number.isFinite(t)&&t>0?t:Math.floor(Ue(e)*We)}function Ct(e,t){let n=J.openSync(e,"r");try{let s=J.fstatSync(n).size,o=Math.min(s,t),r=Buffer.alloc(o);return J.readSync(n,r,0,o,s-o),{text:r.toString("utf8"),truncated:o<s}}finally{J.closeSync(n)}}function It(e,t){let n=e.split(`
13
- `),s=t?1:0;for(let o=n.length-1;o>=s;o--){let r=n[o].trim();if(!r.startsWith("{"))continue;let a;try{a=JSON.parse(r)}catch{continue}if(a?.isSidechain===!0)continue;let l=a?.message?.usage;if(!l)continue;let u=(l.input_tokens||0)+(l.cache_read_input_tokens||0)+(l.cache_creation_input_tokens||0)+(l.output_tokens||0);if(u>0)return u}return null}function Wt(e){if(!e)return{tokens:0,source:"none",bytes:0};let t;try{t=J.statSync(e).size}catch{return{tokens:0,source:"none",bytes:0}}for(let n of At){let s;try{s=Ct(e,n)}catch{break}let o=It(s.text,s.truncated);if(o!=null)return{tokens:o,source:"transcript",bytes:t};if(!s.truncated)break}return{tokens:0,source:"bytes",bytes:t}}function Ut(e){return e.recorded&&!e.stale?"clear":"compact"}function Ht(e,t){return e.recorded?e.stale?`${t}, and the recorded handoff predates the ${e.commits} commit(s) since, so it no longer describes the work in flight`:`${t}, and the handoff is current as of the last commit, so a reset costs only what is not already in that line`:`${t}, and nothing is written down about what this session would lose, so a hard reset would drop it with no way to get it back`}function Je({cwd:e,session:t,transcriptPath:n,bytes:s,usage:o}){let r=o??Wt(n);r.source==="none"&&typeof s=="number"&&(r={tokens:0,source:"bytes",bytes:s});let a=s??r.bytes,l=Dt(r.tokens);if(r.source==="none")return null;let u,i;if(r.source==="transcript"){if(r.tokens<l)return null;u=Math.floor(r.tokens/l),i="this session is at roughly "+Math.round(r.tokens/Ue(r.tokens)*100)+"% of its context window (about "+r.tokens.toLocaleString()+" tokens)"}else{if(a<Ie)return null;u=Math.floor(a/Ie),i=`this session's transcript is ${(a/1024/1024).toFixed(1)} MB (token count unreadable, so this is a rough size signal only)`}let c=se(e,t),p=Ut(c),m=Ht(c,i),d;c.recorded?c.stale?d=`[cairn] Stopping point: ${i}. Clearing now would lose: ${ge(c.text)} \u2014 written before the ${c.commits} commit(s) since.`:d=`[cairn] Stopping point: ${i}. The handoff is current: ${ge(c.text)} \u2014 clearing costs only what is not in that line.`:d=`[cairn] Stopping point: ${i}. Nothing is recorded about what clearing would lose \u2014 ask the user first.`;let h=b=>b===p?" (Recommended)":"",f=[` - "Checkpoint + /clear${h("clear")}" \u2014 I write the handoff now, then you type /clear.`," Full reset and maximum headroom; everything not written down is gone."],g=[` - "Checkpoint + /compact${h("compact")}" \u2014 I write the handoff now, then you type /compact.`," Nothing has to be retyped, but the summary is lossy and the window stays partly full."],_=["STOPPING POINT \u2014 this is the user's call, not yours. Ask them before doing anything else.","",`Use AskUserQuestion. Label the options as ACTIONS, put "(Recommended)" on the ${p}`,`option and list it FIRST, and give them cairn's reason in your own words: ${m}.`,"","Offer exactly these:",...p==="clear"?[...f,...g]:[...g,...f],' - "Keep going" \u2014 decline. Cairn will not raise this again until the situation changes.',"",`Whichever they pick, call cairn_checkpoint FIRST and answer ${O} \u2014 including for`,"/clear, which needs it most, not least. That field is the only part of this session that","survives either option.","","You CANNOT run /clear or /compact yourself: no tool or hook can trigger a slash command.","Say so plainly and ask the user to type it.","","After they type it, cairn's SessionStart hook re-injects the checkpoint automatically, so the","next session starts already knowing where it is. If that does not happen the hook is not",'installed (`cairn install-hooks`) \u2014 in that case tell them to type "resume".',"",`Never write ${O} on their behalf, and never tell them there is nothing outstanding:`,"cairn cannot see what was never written down, so it can never issue an all-clear."].join(`
14
- `),w=[u,r.source,c.recorded?c.stale?"stale":"current":"missing",c.commits??"?",p,n?_e.basename(n):"-"].join("|");return{line:d,guidance:_,signature:w,state:c,recommend:p,reason:m,usage:r,bytes:a}}function Be(e,t){let n=_e.join(e,He);try{if(J.readFileSync(n,"utf8").trim()===t)return!1}catch{}try{J.writeFileSync(n,t,"utf8")}catch{}return!0}function Ye(e){try{J.unlinkSync(_e.join(e,He))}catch{}}var Jt=1e3,Bt=100*1024;function Yt(e,t,n,s){if(e&&typeof e=="object"&&e.ref)return e;let o=typeof e=="string"?e:String(e),r=/^\[\d{4}-\d{2}-\d{2}\]/.test(o)?o:`[${n}] ${o}`;if(r.length<=Jt)return r;let a=Q.join(t,"notes");I.mkdirSync(a,{recursive:!0});let u=`note-${new Date().toISOString().replace(/[:.]/g,"-")}-${s}.md`,i=Q.join(a,u);return I.writeFileSync(i,r,"utf8"),{description:r.split(`
15
- `)[0].slice(0,120),ref:Q.join(".cairn","notes",u)}}function xe(e,{message:t,active_files:n=[],notes:s=[],auto:o=!1,...r}){if(typeof s=="string")try{s=JSON.parse(s)}catch{s=s?[s]:[]}Array.isArray(s)||(s=[]);let a=G(),l=Q.join(a,"session.json"),u=new Date().toISOString().slice(0,10),i=new Date().toISOString(),c={};try{c=JSON.parse(I.readFileSync(l,"utf8"))||{}}catch{}let p=typeof r[O]=="string"&&r[O].trim()?r[O].trim():null,m=p??(typeof c[O]=="string"?c[O]:null),d=p?i:c[`${O}_at`]??null,h={};try{let _=e.prepare("SELECT path FROM main.files").all();for(let{path:w}of _)try{h[w]=I.statSync(w).mtimeMs}catch{}}catch{}for(let _ of n)try{h[_]=I.statSync(_).mtimeMs}catch{}let f=s.map((_,w)=>Yt(_,a,u,w));if(I.existsSync(l))try{if(I.statSync(l).size>Bt){let w=1;for(;I.existsSync(Q.join(a,`session.${w}.json`));)w++;I.renameSync(l,Q.join(a,`session.${w}.json`))}}catch{}let g={message:t,checkpoint_at:i,last_manual_checkpoint_at:o?c.last_manual_checkpoint_at??null:i,last_manual_message:o?c.last_manual_message??null:t,active_files:n,notes:f,[O]:m,[`${O}_at`]:d,mtime_snapshot:h};return I.writeFileSync(l,JSON.stringify(g,null,2),"utf8"),{content:[{type:"text",text:JSON.stringify({saved:!0,checkpoint_at:g.checkpoint_at,active_files_tracked:n.length,notes_saved:f.length,[O]:m?p?"recorded":"carried forward from the previous checkpoint":`not recorded \u2014 nothing will tell the next session what this one would lose (pass ${O})`},null,2)}]}}import H from"fs";import A from"path";import zt from"crypto";var ze=80;function we(e){let t=A.dirname(A.resolve(e)),n=A.parse(t).root;for(;;){let s=A.join(t,".cairn");try{if(H.statSync(s).isDirectory()&&H.existsSync(A.join(s,".cairn-project"))&&s.split(A.sep).filter(r=>r===".cairn").length===1)return s}catch{}if(t===n)return null;t=A.dirname(t)}}function Ge(e,t){let n=zt.createHash("sha256").update(A.resolve(t)).digest("hex").slice(0,6);return A.join(e,"views",`${n}_${A.basename(t)}`)}function K(e){try{return JSON.parse(H.readFileSync(A.join(e,"minify-map.json"),"utf8"))}catch{return{}}}function D(e,t){H.mkdirSync(e,{recursive:!0}),H.writeFileSync(A.join(e,"minify-map.json"),JSON.stringify(t,null,2),"utf8")}function ae(e,t){let n=0;for(let[s,o]of Object.entries(t)){let r=!1;if(!H.existsSync(s))r=!0;else if(!H.existsSync(o.tempPath))r=!0;else try{H.statSync(s).mtimeMs>o.minifiedAt&&(r=!0)}catch{r=!0}if(r){if(o.tempPath)try{H.unlinkSync(o.tempPath)}catch{}delete t[s],n++}}return n}function Ke(e,t){switch(t){case"javascript":case"typescript":return be(e);case"java":return be(e,{annotations:!0});case"python":return Vt(e);case"vue":return Xt(e);case"sql":return Zt(e);default:return e.split(`
10
+ `)}import I from"fs";import ee from"path";import M from"fs";import Nt from"os";import C from"path";var ye=null;function z(){return ye||process.cwd()}function Ce(e){let t=ye;return ye=e,t}function G(){let e=C.join(z(),".cairn");M.mkdirSync(C.join(e,"bundles"),{recursive:!0});let t=C.join(e,".cairn-project");return M.existsSync(t)||M.writeFileSync(t,"","utf8"),e}function ge(e){return e.replace(/[:/\\]/g,"-").replace(/^-+/,"")}function _e(){let e=C.join(Nt.homedir(),".claude","projects",ge(z()));return M.existsSync(e)?C.join(e,"memory"):null}function De(e){let t=C.join(e,"MEMORY.md");M.existsSync(t)||M.writeFileSync(t,`# Memory Index
11
+ `,"utf8")}function Se(){let e=C.join(G(),"memory");M.mkdirSync(e,{recursive:!0}),De(e);let t=_e();if(!t)return e;M.mkdirSync(t,{recursive:!0}),De(t);let n=s=>M.readdirSync(s).some(o=>o.endsWith(".md")&&o!=="MEMORY.md");if(!n(t)&&n(e))for(let s of M.readdirSync(e)){let o=C.join(e,s);try{if(!M.statSync(o).isFile())continue;let r=M.statSync(o);M.copyFileSync(o,C.join(t,s));try{M.utimesSync(C.join(t,s),r.atime,r.mtime)}catch{}}catch{}}return t}import J from"fs";import we from"path";import{execSync as Mt}from"child_process";var O="would_be_lost";var Ie=2*1024*1024,le=[2e5,1e6],We=.9;function Ue(e){for(let t of le)if(e<=t*.98)return t;return le[le.length-1]}var ks=le[0]*We,At=[256*1024,1024*1024],He=".handoff-hint",Ft=220;function xe(e,t=Ft){let n=String(e).replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Lt(e,t){try{let n=Mt(`git log --oneline --after="${t}"`,{cwd:e,encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n?n.split(`
12
+ `).length:0}catch{return null}}function re(e,t){let n=typeof t?.[O]=="string"?t[O].trim():"";if(!n)return{recorded:!1,text:"",at:null,commits:null,stale:!1};let s=t[`${O}_at`]||t.checkpoint_at||null,o=s?Lt(e,s):null;return{recorded:!0,text:n,at:s,commits:o,stale:(o??0)>0}}function be(e){if(!e.recorded)return"No handoff recorded \u2014 nothing was written down about what the last session would lose.";let t=e.stale?` (written before the ${e.commits} commit(s) since \u2014 may be stale)`:"";return`Carried forward: ${xe(e.text)}${t}`}function Dt(e=0){let t=Number(process.env.CAIRN_CONTEXT_HINT_TOKENS);return Number.isFinite(t)&&t>0?t:Math.floor(Ue(e)*We)}function Ct(e,t){let n=J.openSync(e,"r");try{let s=J.fstatSync(n).size,o=Math.min(s,t),r=Buffer.alloc(o);return J.readSync(n,r,0,o,s-o),{text:r.toString("utf8"),truncated:o<s}}finally{J.closeSync(n)}}function It(e,t){let n=e.split(`
13
+ `),s=t?1:0;for(let o=n.length-1;o>=s;o--){let r=n[o].trim();if(!r.startsWith("{"))continue;let a;try{a=JSON.parse(r)}catch{continue}if(a?.isSidechain===!0)continue;let c=a?.message?.usage;if(!c)continue;let u=(c.input_tokens||0)+(c.cache_read_input_tokens||0)+(c.cache_creation_input_tokens||0)+(c.output_tokens||0);if(u>0)return u}return null}function Wt(e){if(!e)return{tokens:0,source:"none",bytes:0};let t;try{t=J.statSync(e).size}catch{return{tokens:0,source:"none",bytes:0}}for(let n of At){let s;try{s=Ct(e,n)}catch{break}let o=It(s.text,s.truncated);if(o!=null)return{tokens:o,source:"transcript",bytes:t};if(!s.truncated)break}return{tokens:0,source:"bytes",bytes:t}}function Ut(e){return e.recorded&&!e.stale?"clear":"compact"}function Ht(e,t){return e.recorded?e.stale?`${t}, and the recorded handoff predates the ${e.commits} commit(s) since, so it no longer describes the work in flight`:`${t}, and the handoff is current as of the last commit, so a reset costs only what is not already in that line`:`${t}, and nothing is written down about what this session would lose, so a hard reset would drop it with no way to get it back`}function Je({cwd:e,session:t,transcriptPath:n,bytes:s,usage:o}){let r=o??Wt(n);r.source==="none"&&typeof s=="number"&&(r={tokens:0,source:"bytes",bytes:s});let a=s??r.bytes,c=Dt(r.tokens);if(r.source==="none")return null;let u,i;if(r.source==="transcript"){if(r.tokens<c)return null;u=Math.floor(r.tokens/c),i="this session is at roughly "+Math.round(r.tokens/Ue(r.tokens)*100)+"% of its context window (about "+r.tokens.toLocaleString()+" tokens)"}else{if(a<Ie)return null;u=Math.floor(a/Ie),i=`this session's transcript is ${(a/1024/1024).toFixed(1)} MB (token count unreadable, so this is a rough size signal only)`}let l=re(e,t),d=Ut(l),f=Ht(l,i),p;l.recorded?l.stale?p=`[cairn] Stopping point: ${i}. Clearing now would lose: ${xe(l.text)} \u2014 written before the ${l.commits} commit(s) since.`:p=`[cairn] Stopping point: ${i}. The handoff is current: ${xe(l.text)} \u2014 clearing costs only what is not in that line.`:p=`[cairn] Stopping point: ${i}. Nothing is recorded about what clearing would lose \u2014 ask the user first.`;let h=b=>b===d?" (Recommended)":"",m=[` - "Checkpoint + /clear${h("clear")}" \u2014 I write the handoff now, then you type /clear.`," Full reset and maximum headroom; everything not written down is gone."],_=[` - "Checkpoint + /compact${h("compact")}" \u2014 I write the handoff now, then you type /compact.`," Nothing has to be retyped, but the summary is lossy and the window stays partly full."],g=["STOPPING POINT \u2014 this is the user's call, not yours. Ask them before doing anything else.","",`Use AskUserQuestion. Label the options as ACTIONS, put "(Recommended)" on the ${d}`,`option and list it FIRST, and give them cairn's reason in your own words: ${f}.`,"","Offer exactly these:",...d==="clear"?[...m,..._]:[..._,...m],' - "Keep going" \u2014 decline. Cairn will not raise this again until the situation changes.',"",`Whichever they pick, call cairn_checkpoint FIRST and answer ${O} \u2014 including for`,"/clear, which needs it most, not least. That field is the only part of this session that","survives either option.","","You CANNOT run /clear or /compact yourself: no tool or hook can trigger a slash command.","Say so plainly and ask the user to type it.","","After they type it, cairn's SessionStart hook re-injects the checkpoint automatically, so the","next session starts already knowing where it is. If that does not happen the hook is not",'installed (`cairn install-hooks`) \u2014 in that case tell them to type "resume".',"",`Never write ${O} on their behalf, and never tell them there is nothing outstanding:`,"cairn cannot see what was never written down, so it can never issue an all-clear."].join(`
14
+ `),S=[u,r.source,l.recorded?l.stale?"stale":"current":"missing",l.commits??"?",d,n?we.basename(n):"-"].join("|");return{line:p,guidance:g,signature:S,state:l,recommend:d,reason:f,usage:r,bytes:a}}function Be(e,t){let n=we.join(e,He);try{if(J.readFileSync(n,"utf8").trim()===t)return!1}catch{}try{J.writeFileSync(n,t,"utf8")}catch{}return!0}function Ye(e){try{J.unlinkSync(we.join(e,He))}catch{}}var Jt=1e3,Bt=100*1024;function Yt(e,t,n,s){if(e&&typeof e=="object"&&e.ref)return e;let o=typeof e=="string"?e:String(e),r=/^\[\d{4}-\d{2}-\d{2}\]/.test(o)?o:`[${n}] ${o}`;if(r.length<=Jt)return r;let a=ee.join(t,"notes");I.mkdirSync(a,{recursive:!0});let u=`note-${new Date().toISOString().replace(/[:.]/g,"-")}-${s}.md`,i=ee.join(a,u);return I.writeFileSync(i,r,"utf8"),{description:r.split(`
15
+ `)[0].slice(0,120),ref:ee.join(".cairn","notes",u)}}function ke(e,{message:t,active_files:n=[],notes:s=[],auto:o=!1,...r}){if(typeof s=="string")try{s=JSON.parse(s)}catch{s=s?[s]:[]}Array.isArray(s)||(s=[]);let a=G(),c=ee.join(a,"session.json"),u=new Date().toISOString().slice(0,10),i=new Date().toISOString(),l={};try{l=JSON.parse(I.readFileSync(c,"utf8"))||{}}catch{}let d=typeof r[O]=="string"&&r[O].trim()?r[O].trim():null,f=d??(typeof l[O]=="string"?l[O]:null),p=d?i:l[`${O}_at`]??null,h={};try{let g=e.prepare("SELECT path FROM main.files").all();for(let{path:S}of g)try{h[S]=I.statSync(S).mtimeMs}catch{}}catch{}for(let g of n)try{h[g]=I.statSync(g).mtimeMs}catch{}let m=s.map((g,S)=>Yt(g,a,u,S));if(I.existsSync(c))try{if(I.statSync(c).size>Bt){let S=1;for(;I.existsSync(ee.join(a,`session.${S}.json`));)S++;I.renameSync(c,ee.join(a,`session.${S}.json`))}}catch{}let _={message:t,checkpoint_at:i,last_manual_checkpoint_at:o?l.last_manual_checkpoint_at??null:i,last_manual_message:o?l.last_manual_message??null:t,active_files:n,notes:m,[O]:f,[`${O}_at`]:p,mtime_snapshot:h};return I.writeFileSync(c,JSON.stringify(_,null,2),"utf8"),{content:[{type:"text",text:JSON.stringify({saved:!0,checkpoint_at:_.checkpoint_at,active_files_tracked:n.length,notes_saved:m.length,[O]:f?d?"recorded":"carried forward from the previous checkpoint":`not recorded \u2014 nothing will tell the next session what this one would lose (pass ${O})`},null,2)}]}}import H from"fs";import A from"path";import zt from"crypto";var ze=80;function Ee(e){let t=A.dirname(A.resolve(e)),n=A.parse(t).root;for(;;){let s=A.join(t,".cairn");try{if(H.statSync(s).isDirectory()&&H.existsSync(A.join(s,".cairn-project"))&&s.split(A.sep).filter(r=>r===".cairn").length===1)return s}catch{}if(t===n)return null;t=A.dirname(t)}}function Ge(e,t){let n=zt.createHash("sha256").update(A.resolve(t)).digest("hex").slice(0,6);return A.join(e,"views",`${n}_${A.basename(t)}`)}function K(e){try{return JSON.parse(H.readFileSync(A.join(e,"minify-map.json"),"utf8"))}catch{return{}}}function D(e,t){H.mkdirSync(e,{recursive:!0}),H.writeFileSync(A.join(e,"minify-map.json"),JSON.stringify(t,null,2),"utf8")}function ue(e,t){let n=0;for(let[s,o]of Object.entries(t)){let r=!1;if(!H.existsSync(s))r=!0;else if(!H.existsSync(o.tempPath))r=!0;else try{H.statSync(s).mtimeMs>o.minifiedAt&&(r=!0)}catch{r=!0}if(r){if(o.tempPath)try{H.unlinkSync(o.tempPath)}catch{}delete t[s],n++}}return n}function Ke(e,t){switch(t){case"javascript":case"typescript":return $e(e);case"java":return $e(e,{annotations:!0});case"python":return Vt(e);case"vue":return Xt(e);case"sql":return Zt(e);default:return e.split(`
16
16
  `).slice(0,30).join(`
17
17
  `)+`
18
- ...`}}function be(e,{annotations:t=!1}={}){let n=e.split(`
19
- `),s=[],o=0;for(let r=0;r<n.length;r++){let a=n[r].trim();if(!a)continue;let{opens:l,closes:u}=qt(a),i=l-u;if(o===0){let c=Gt(a);c!==null?s.push(`${r+1}: ${c}`):a==="}"&&s.push("}")}else if(o===1){let c=Kt(a,t);c!==null&&s.push(` ${r+1}: ${c}`)}o=Math.max(0,o+i)}return s.join(`
18
+ ...`}}function $e(e,{annotations:t=!1}={}){let n=e.split(`
19
+ `),s=[],o=0;for(let r=0;r<n.length;r++){let a=n[r].trim();if(!a)continue;let{opens:c,closes:u}=qt(a),i=c-u;if(o===0){let l=Gt(a);l!==null?s.push(`${r+1}: ${l}`):a==="}"&&s.push("}")}else if(o===1){let l=Kt(a,t);l!==null&&s.push(` ${r+1}: ${l}`)}o=Math.max(0,o+i)}return s.join(`
20
20
  `)}function Gt(e){return/^import\s/.test(e)||/^@\w+/.test(e)||/^package\s/.test(e)?e:/^export\s/.test(e)?/^export\s+(default\s+)?(async\s+)?function[\s*]|^export\s+(default\s+)?(abstract\s+)?class\s/.test(e)?W(e):e:/^(async\s+)?function[\s*]/.test(e)||/^(abstract\s+)?class\s/.test(e)||/^(public\s+|private\s+|protected\s+)?(interface|enum|type|record)\s/.test(e)||/^(const|let|var)\s+\w+/.test(e)||/^(public|private|protected|abstract|final)\s+(class|interface|enum)\s/.test(e)?W(e):e==="}"?"}":null}function Kt(e,t){return t&&/^@\w+/.test(e)?e:e==="}"?"}":/^(public|private|protected|static|final|abstract|async|override|readonly|synchronized|native)\s/.test(e)||/^constructor\s*\(/.test(e)||/^(get|set)\s+\w+\s*\(/.test(e)||/^\w[\w$]*\s*[<(]/.test(e)&&!e.startsWith("return")&&!e.startsWith("throw")&&!e.startsWith("if")&&!e.startsWith("for")&&!e.startsWith("while")&&!e.startsWith("switch")&&!e.startsWith("const")&&!e.startsWith("let")&&!e.startsWith("var")?W(e):null}function W(e){let t=0,n=!1,s="";for(let o=0;o<e.length;o++){let r=e[o];if(n)r===s&&e[o-1]!=="\\"&&(n=!1);else if(r==='"'||r==="'"||r==="`")n=!0,s=r;else if(r==="{"){if(t===0)return e.slice(0,o).trimEnd();t++}else r==="}"&&t--}return e}function qt(e){let t=0,n=0,s=!1,o="";for(let r=0;r<e.length;r++){let a=e[r];s?a===o&&e[r-1]!=="\\"&&(s=!1):a==='"'||a==="'"||a==="`"?(s=!0,o=a):a==="{"?t++:a==="}"&&n++}return{opens:t,closes:n}}function Vt(e){let t=[],n=e.split(`
21
21
  `);for(let s=0;s<n.length;s++){let o=n[s];if(!o.trim())continue;let r=o.trimStart();r.startsWith("import ")||r.startsWith("from ")?t.push(o):(r.startsWith("class ")||r.startsWith("def ")||r.startsWith("async def "))&&t.push(`${s+1}: ${o.trim().replace(/:(\s*)$/,":")}`)}return t.join(`
22
- `)}function Xt(e){let t=[];for(let s of e.matchAll(/<(template|script|style)(\s[^>]*)?\s*>/g))t.push(s[0]);let n=e.match(/<script(?:\s[^>]*)?\s*>([\s\S]*?)<\/script>/);if(n){let s=be(n[1]);s.trim()&&(t.push("// script:"),t.push(s))}return t.join(`
22
+ `)}function Xt(e){let t=[];for(let s of e.matchAll(/<(template|script|style)(\s[^>]*)?\s*>/g))t.push(s[0]);let n=e.match(/<script(?:\s[^>]*)?\s*>([\s\S]*?)<\/script>/);if(n){let s=$e(n[1]);s.trim()&&(t.push("// script:"),t.push(s))}return t.join(`
23
23
  `)}function Zt(e){let t=[],n=e.split(`
24
24
  `);for(let s=0;s<n.length;s++){let o=n[s].trim();/^(CREATE|ALTER|DROP|INSERT|UPDATE|DELETE|SELECT|WITH|GRANT|REVOKE|BEGIN|COMMIT)\b/i.test(o)&&t.push(`${s+1}: ${o.slice(0,120)}${o.length>120?"...":""}`)}return t.join(`
25
- `)}import F from"fs";import B from"path";var Qt=["preference","experience","decision","knowledge"];function oe(e){if(!e||typeof e!="string")return[];let t=e.split(/\r?\n/),n=!1,s=null,o=[],r=new Set;for(let a of t){if(/^##\s+Phases\s*$/i.test(a)){n=!0;continue}if(/^##\s+/.test(a)&&!/^###/.test(a)){s&&(o.push(s),s=null),n=!1;continue}if(!n)continue;let l=/^###\s+Phase\s+(\d+)\s*:\s*(.+?)\s*$/.exec(a);if(l){s&&o.push(s);let u=parseInt(l[1],10),i=l[2];if(r.has(u)){process.stderr.write(`[cairn] memo phase parser: duplicate Phase ${u} ignored
25
+ `)}import F from"fs";import B from"path";var Qt=["preference","experience","decision","knowledge"];function ie(e){if(!e||typeof e!="string")return[];let t=e.split(/\r?\n/),n=!1,s=null,o=[],r=new Set;for(let a of t){if(/^##\s+Phases\s*$/i.test(a)){n=!0;continue}if(/^##\s+/.test(a)&&!/^###/.test(a)){s&&(o.push(s),s=null),n=!1;continue}if(!n)continue;let c=/^###\s+Phase\s+(\d+)\s*:\s*(.+?)\s*$/.exec(a);if(c){s&&o.push(s);let u=parseInt(c[1],10),i=c[2];if(r.has(u)){process.stderr.write(`[cairn] memo phase parser: duplicate Phase ${u} ignored
26
26
  `),s=null;continue}r.add(u),s={phase_number:u,text:i,bodyLines:[]};continue}s&&s.bodyLines.push(a)}return s&&o.push(s),o.map(a=>({phase_number:a.phase_number,text:a.text,body:a.bodyLines.join(`
27
- `).trim()||null}))}var qe=(e,t)=>e+" :: "+t;function Xe(e,t,n,s={}){let o=e.prepare("SELECT id, phase_number, status, text FROM main.roadmap_phases WHERE decision_name = ? AND phase_number IS NOT NULL ORDER BY phase_number").all(t),r=new Map(o.map(b=>[b.phase_number,b])),a=new Set,l=e.prepare("UPDATE main.roadmap_phases SET text = ?, body = ?, status = CASE WHEN status = ? THEN ? ELSE status END WHERE id = ?"),u=e.prepare("INSERT INTO main.roadmap_phases (decision_name, phase_number, parent_phase_id, text, body, status, position) VALUES (?, ?, NULL, ?, ?, ?, ?)"),i=e.prepare("UPDATE main.roadmap_phases SET status = 'stale' WHERE id = ?"),c=e.prepare("UPDATE main.roadmap_phases SET phase_number = NULL WHERE id = ?"),p=e.prepare("UPDATE main.roadmap_phases SET text = ?, body = ?, status = 'open', resolved_at = NULL WHERE id = ?"),m=s.completed??null,d=m===null?null:new Set(m.map(b=>qe(b.number,b.title))),h=[],f=[],g=[],_=[],w=[];for(let b=0;b<n.length;b++){let x=n[b];a.add(x.phase_number);let k=r.get(x.phase_number);if(k&&k.status==="done"&&k.text!==x.text){c.run(k.id);let L=u.run(t,x.phase_number,x.text,x.body,"open",b);_.push({id:Number(L.lastInsertRowid),phase_number:x.phase_number,text:x.text,replaced_shipped:k.id})}else if(k&&k.status==="done"&&d!==null&&!d.has(qe(x.phase_number,x.text)))p.run(x.text,x.body,k.id),h.push({id:k.id,phase_number:x.phase_number,text:x.text});else if(k)l.run(x.text,x.body,"stale","open",k.id),g.push({id:k.id,phase_number:x.phase_number,text:x.text,reactivated:k.status==="stale"});else{let L=u.run(t,x.phase_number,x.text,x.body,"open",b);_.push({id:Number(L.lastInsertRowid),phase_number:x.phase_number,text:x.text})}}for(let[b,x]of r)!a.has(b)&&x.status!=="stale"&&x.status!=="done"&&(i.run(x.id),w.push({id:x.id,phase_number:b}));if(h.length>0){let b=n.reduce((x,k)=>Math.max(x,k.phase_number),0);for(let[x,k]of r)k.status==="done"&&x>b&&(c.run(k.id),f.push({id:k.id,phase_number:x,text:k.text}))}return{updated:g.length,inserted:_.length,staled:w.length,repaired:h.length,retired:f.length,updated_phases:g,inserted_phases:_,staled_phases:w,repaired_phases:h,retired_phases:f}}function en(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return{};let n={};for(let s of t[1].split(`
28
- `)){let o=s.indexOf(":");o!==-1&&(n[s.slice(0,o).trim()]=s.slice(o+1).trim())}return n}function tn(e){let t=B.join(e,"MEMORY.md");return F.existsSync(t)?F.readFileSync(t,"utf8"):""}var nn=/^- \[(.+?)\]\((.+?)\)\s+—\s+(.*?)(?:\s+`\[(.+?)\]`)?\s*$/;function Ze(e){let t=nn.exec(e);return t?{name:t[1],file:t[2],description:t[3],type:t[4]||null}:null}function Ve(e){let t="- ["+e.name+"]("+e.file+") \u2014 "+e.description;return e.type?t+" `["+e.type+"]`":t}function sn(e,t){let n=B.join(e,"MEMORY.md"),s=new Map(t.map(l=>[l.file,l])),o=new Set,r=F.existsSync(n)?F.readFileSync(n,"utf8").split(`
29
- `):["# Memory Index",""],a=[];for(let l of r){let u=Ze(l);if(!u){a.push(l);continue}let i=s.get(u.file);!i||o.has(i.file)||(o.add(i.file),a.push(Ve(i)))}for(;a.length>0&&a[a.length-1].trim()==="";)a.pop();for(let l of t)o.has(l.file)||(o.add(l.file),a.push(Ve(l)));F.writeFileSync(n,a.join(`
27
+ `).trim()||null}))}var qe=(e,t)=>e+" :: "+t;function Xe(e,t,n,s={}){let o=e.prepare("SELECT id, phase_number, status, text FROM main.roadmap_phases WHERE decision_name = ? AND phase_number IS NOT NULL ORDER BY phase_number").all(t),r=new Map(o.map(b=>[b.phase_number,b])),a=new Set,c=e.prepare("UPDATE main.roadmap_phases SET text = ?, body = ?, status = CASE WHEN status = ? THEN ? ELSE status END WHERE id = ?"),u=e.prepare("INSERT INTO main.roadmap_phases (decision_name, phase_number, parent_phase_id, text, body, status, position) VALUES (?, ?, NULL, ?, ?, ?, ?)"),i=e.prepare("UPDATE main.roadmap_phases SET status = 'stale' WHERE id = ?"),l=e.prepare("UPDATE main.roadmap_phases SET phase_number = NULL WHERE id = ?"),d=e.prepare("UPDATE main.roadmap_phases SET text = ?, body = ?, status = 'open', resolved_at = NULL WHERE id = ?"),f=s.completed??null,p=f===null?null:new Set(f.map(b=>qe(b.number,b.title))),h=[],m=[],_=[],g=[],S=[];for(let b=0;b<n.length;b++){let w=n[b];a.add(w.phase_number);let k=r.get(w.phase_number);if(k&&k.status==="done"&&k.text!==w.text){l.run(k.id);let L=u.run(t,w.phase_number,w.text,w.body,"open",b);g.push({id:Number(L.lastInsertRowid),phase_number:w.phase_number,text:w.text,replaced_shipped:k.id})}else if(k&&k.status==="done"&&p!==null&&!p.has(qe(w.phase_number,w.text)))d.run(w.text,w.body,k.id),h.push({id:k.id,phase_number:w.phase_number,text:w.text});else if(k)c.run(w.text,w.body,"stale","open",k.id),_.push({id:k.id,phase_number:w.phase_number,text:w.text,reactivated:k.status==="stale"});else{let L=u.run(t,w.phase_number,w.text,w.body,"open",b);g.push({id:Number(L.lastInsertRowid),phase_number:w.phase_number,text:w.text})}}for(let[b,w]of r)!a.has(b)&&w.status!=="stale"&&w.status!=="done"&&(i.run(w.id),S.push({id:w.id,phase_number:b}));if(h.length>0){let b=n.reduce((w,k)=>Math.max(w,k.phase_number),0);for(let[w,k]of r)k.status==="done"&&w>b&&(l.run(k.id),m.push({id:k.id,phase_number:w,text:k.text}))}return{updated:_.length,inserted:g.length,staled:S.length,repaired:h.length,retired:m.length,updated_phases:_,inserted_phases:g,staled_phases:S,repaired_phases:h,retired_phases:m}}function en(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return{};let n={};for(let s of t[1].split(`
28
+ `)){let o=s.indexOf(":");o!==-1&&(n[s.slice(0,o).trim()]=s.slice(o+1).trim())}return n}function tn(e){let t=B.join(e,"MEMORY.md");return F.existsSync(t)?F.readFileSync(t,"utf8"):""}var nn=/^- \[(.+?)\]\((.+?)\)\s+—\s+(.*?)(?:\s+`\[(.+?)\]`)?\s*$/;function Ze(e){let t=nn.exec(e);return t?{name:t[1],file:t[2],description:t[3],type:t[4]||null}:null}function Ve(e){let t="- ["+e.name+"]("+e.file+") \u2014 "+e.description;return e.type?t+" `["+e.type+"]`":t}function sn(e,t){let n=B.join(e,"MEMORY.md"),s=new Map(t.map(c=>[c.file,c])),o=new Set,r=F.existsSync(n)?F.readFileSync(n,"utf8").split(`
29
+ `):["# Memory Index",""],a=[];for(let c of r){let u=Ze(c);if(!u){a.push(c);continue}let i=s.get(u.file);!i||o.has(i.file)||(o.add(i.file),a.push(Ve(i)))}for(;a.length>0&&a[a.length-1].trim()==="";)a.pop();for(let c of t)o.has(c.file)||(o.add(c.file),a.push(Ve(c)));F.writeFileSync(n,a.join(`
30
30
  `).replace(/\n{3,}/g,`
31
31
 
32
32
  `)+`
33
33
  `,"utf8")}function on(e){let t=[];for(let n of tn(e).split(`
34
- `)){let s=Ze(n);s&&t.push(s)}return t}function rn(e){let t=B.join(e,"MEMORY.bak");if(!F.existsSync(t))return t;for(let n=2;n<=1e3;n++){let s=B.join(e,"MEMORY.bak."+n);if(!F.existsSync(s))return s}return null}function Qe(e,{dryRun:t=!1}={}){if(!F.existsSync(e))return{repaired:!1,reason:"no memory directory",dir:e};let n=on(e),s=new Set(n.map(i=>i.file)),o=F.readdirSync(e).filter(i=>i.endsWith(".md")&&i!=="MEMORY.md"&&!/^MEMORY\.bak(\.\d+)?\.md$/.test(i)).sort(),r=[],a=[];for(let i of o){if(s.has(i))continue;let c;try{c=en(F.readFileSync(B.join(e,i),"utf8"))}catch(p){a.push({file:i,reason:p.message});continue}r.push({name:c.name||i.replace(/\.md$/,""),file:i,description:c.description||"(no description in frontmatter)",type:Qt.includes(c.type)?c.type:null})}let l=n.filter(i=>!F.existsSync(B.join(e,i.file))).map(i=>({name:i.name,file:i.file})),u=null;if(r.length>0&&!t){let i=rn(e);if(i)try{F.copyFileSync(B.join(e,"MEMORY.md"),i),u=B.basename(i)}catch{}sn(e,[...n,...r])}return{repaired:r.length>0&&!t,dry_run:t,dir:e,files_on_disk:o.length,already_indexed:n.length,restored:r.length,restored_entries:r.map(i=>({name:i.name,file:i.file,type:i.type})),dangling:l,unreadable:a,backup:u}}import v from"fs";import ee from"path";var T="roadmap",an=`# Roadmap
34
+ `)){let s=Ze(n);s&&t.push(s)}return t}function rn(e){let t=B.join(e,"MEMORY.bak");if(!F.existsSync(t))return t;for(let n=2;n<=1e3;n++){let s=B.join(e,"MEMORY.bak."+n);if(!F.existsSync(s))return s}return null}function Qe(e,{dryRun:t=!1}={}){if(!F.existsSync(e))return{repaired:!1,reason:"no memory directory",dir:e};let n=on(e),s=new Set(n.map(i=>i.file)),o=F.readdirSync(e).filter(i=>i.endsWith(".md")&&i!=="MEMORY.md"&&!/^MEMORY\.bak(\.\d+)?\.md$/.test(i)).sort(),r=[],a=[];for(let i of o){if(s.has(i))continue;let l;try{l=en(F.readFileSync(B.join(e,i),"utf8"))}catch(d){a.push({file:i,reason:d.message});continue}r.push({name:l.name||i.replace(/\.md$/,""),file:i,description:l.description||"(no description in frontmatter)",type:Qt.includes(l.type)?l.type:null})}let c=n.filter(i=>!F.existsSync(B.join(e,i.file))).map(i=>({name:i.name,file:i.file})),u=null;if(r.length>0&&!t){let i=rn(e);if(i)try{F.copyFileSync(B.join(e,"MEMORY.md"),i),u=B.basename(i)}catch{}sn(e,[...n,...r])}return{repaired:r.length>0&&!t,dry_run:t,dir:e,files_on_disk:o.length,already_indexed:n.length,restored:r.length,restored_entries:r.map(i=>({name:i.name,file:i.file,type:i.type})),dangling:c,unreadable:a,backup:u}}import v from"fs";import te from"path";var j="roadmap",an=`# Roadmap
35
35
 
36
36
  The forward-looking plan: only upcoming and in-progress phases live here. When a
37
37
  phase is marked done (cairn_roadmap set_status <id> done) it is removed from this
@@ -42,77 +42,73 @@ the plan \u2014 Cairn syncs it into the live tracker on the next cairn_roadmap r
42
42
 
43
43
  ### Phase 1: First phase title
44
44
  What this phase delivers.
45
- `;function q(){return ee.join(G(),"roadmap.md")}function cn(){return ee.join(G(),"roadmap_completed.md")}function ce(){let e=q();return v.existsSync(e)?v.readFileSync(e,"utf8"):""}function Ee(){let e=q();return v.existsSync(e)?!1:(v.writeFileSync(e,an,"utf8"),!0)}function ln(e){let t=[];for(let n of e){let s=(n.text||"").trim();s&&(!Number.isInteger(n.phase_number)||n.phase_number<1||t.push({phase_number:n.phase_number,text:s,body:n.body??null}))}return t}var ke="decision_production_roadmap.md";function un(e){let t=e.match(/^---\n[\s\S]*?\n---\n?/);return t?e.slice(t[0].length):e}function pn(e,t){let n=ee.join(e,"MEMORY.md");if(!v.existsSync(n))return;let s=v.readFileSync(n,"utf8").split(/\r?\n/).filter(o=>!o.includes(`](${t})`));v.writeFileSync(n,s.join(`
46
- `),"utf8")}function dn(){let e=q();if(v.existsSync(e))return null;let t=[],n=he();n&&t.push(n),t.push(ee.join(G(),"memory"));let s=null,o=null;for(let a of t){let l=ee.join(a,ke);s==null&&v.existsSync(l)&&(s=un(v.readFileSync(l,"utf8")).trim(),o=l)}if(s==null)return null;let r=/^#\s/m.test(s)?"":`# Roadmap
45
+ `;function q(){return te.join(G(),"roadmap.md")}function cn(){return te.join(G(),"roadmap_completed.md")}function de(){let e=q();return v.existsSync(e)?v.readFileSync(e,"utf8"):""}function ve(){let e=q();return v.existsSync(e)?!1:(v.writeFileSync(e,an,"utf8"),!0)}function ln(e){let t=[];for(let n of e){let s=(n.text||"").trim();s&&(!Number.isInteger(n.phase_number)||n.phase_number<1||t.push({phase_number:n.phase_number,text:s,body:n.body??null}))}return t}var Re="decision_production_roadmap.md";function un(e){let t=e.match(/^---\n[\s\S]*?\n---\n?/);return t?e.slice(t[0].length):e}function dn(e,t){let n=te.join(e,"MEMORY.md");if(!v.existsSync(n))return;let s=v.readFileSync(n,"utf8").split(/\r?\n/).filter(o=>!o.includes(`](${t})`));v.writeFileSync(n,s.join(`
46
+ `),"utf8")}function pn(){let e=q();if(v.existsSync(e))return null;let t=[],n=_e();n&&t.push(n),t.push(te.join(G(),"memory"));let s=null,o=null;for(let a of t){let c=te.join(a,Re);s==null&&v.existsSync(c)&&(s=un(v.readFileSync(c,"utf8")).trim(),o=c)}if(s==null)return null;let r=/^#\s/m.test(s)?"":`# Roadmap
47
47
 
48
48
  `;v.writeFileSync(e,r+s+`
49
- `,"utf8");for(let a of t){let l=ee.join(a,ke);try{v.existsSync(l)&&v.unlinkSync(l)}catch{}try{pn(a,ke)}catch{}}return{migrated:!0,from:o,to:e}}function te(e){dn();let t=q();if(!v.existsSync(t))return null;let n=v.readFileSync(t,"utf8");if(!/^##\s+Phases\s*$/im.test(n))return null;let s=ln(oe(n));return Xe(e,T,s,{completed:$e()})}var fn=/^-\s+(\d{4}-\d{2}-\d{2})\s+—\s+Phase\s+(\d+):\s*(.+?)(?:\s+\(([^)]*)\))?\s*$/,et=/^phase-(\d+)$/,mn=/^[0-9a-f]{7,40}$/;function $e(){let e=cn();if(!v.existsSync(e))return null;let t=[];for(let n of v.readFileSync(e,"utf8").split(/\r?\n/)){let s=fn.exec(n);if(!s)continue;let o=s[3],r=null,a=null;if(s[4]!=null){let l=s[4].split(/\s*,\s*/).filter(Boolean);if(l.length>0&&l.every(i=>et.test(i)||mn.test(i)))for(let i of l){let c=et.exec(i);c?r=parseInt(c[1],10):a=i}else o=`${o} (${s[4]})`}t.push({date:s[1],number:parseInt(s[2],10),title:o,id:r,commit:a})}return t}import ne from"fs";import Re from"path";import{execSync as hn}from"child_process";var tt=120;function Oe(e){if(!e)return"";let t=String(e).replace(/`([^`]*)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/^[-*+\s]+/,"").replace(/^#{1,6}\s*/,"").replace(/[*~]/g,"").replace(/\s+/g," ").trim().replace(/[::.\s]+$/,"");return t.length>tt&&(t=t.slice(0,tt-1).trimEnd()+"\u2026"),t}function Y(e){return String(e||"").toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function yn(e){if(!e||typeof e!="string")return[];let t=e.split(/\r?\n/),n=i=>i.map(c=>({text:Oe(c.titleRaw),body:c.bodyLines.join(`
50
- `).trim()||null})).filter(c=>c.text),s=[],o=null;for(let i of t){let c=/^(#{1,6})\s+(.+?)\s*$/.exec(i);if(c&&c[1].length>=2&&c[1].length<=4){o&&s.push(o),o={titleRaw:c[2],bodyLines:[]};continue}o&&o.bodyLines.push(i)}o&&s.push(o);let r=[];o=null;for(let i of t){let c=/^(\d+)[.)]\s+(.+?)\s*$/.exec(i);if(c){o&&r.push(o),o={titleRaw:c[2],bodyLines:[]};continue}o&&o.bodyLines.push(i)}o&&r.push(o);let a=[n(s),n(r)].filter(i=>i.length>=2);if(a.length)return a.sort((i,c)=>c.length-i.length),a[0];let l=t.find(i=>i.trim());return[{text:Oe(l||"Plan")||"Plan",body:e.trim()||null}]}function gn(e){let t=[];return e.forEach((n,s)=>{t.push(`### Phase ${s+1}: ${n.text}`),n.body&&n.body.trim()&&t.push(n.body.trim()),t.push("")}),t.join(`
49
+ `,"utf8");for(let a of t){let c=te.join(a,Re);try{v.existsSync(c)&&v.unlinkSync(c)}catch{}try{dn(a,Re)}catch{}}return{migrated:!0,from:o,to:e}}function ne(e){pn();let t=q();if(!v.existsSync(t))return null;let n=v.readFileSync(t,"utf8");if(!/^##\s+Phases\s*$/im.test(n))return null;let s=ln(ie(n));return Xe(e,j,s,{completed:Oe()})}var fn=/^-\s+(\d{4}-\d{2}-\d{2})\s+—\s+Phase\s+(\d+):\s*(.+?)(?:\s+\(([^)]*)\))?\s*$/,et=/^phase-(\d+)$/,mn=/^[0-9a-f]{7,40}$/;function Oe(){let e=cn();if(!v.existsSync(e))return null;let t=[];for(let n of v.readFileSync(e,"utf8").split(/\r?\n/)){let s=fn.exec(n);if(!s)continue;let o=s[3],r=null,a=null;if(s[4]!=null){let c=s[4].split(/\s*,\s*/).filter(Boolean);if(c.length>0&&c.every(i=>et.test(i)||mn.test(i)))for(let i of c){let l=et.exec(i);l?r=parseInt(l[1],10):a=i}else o=`${o} (${s[4]})`}t.push({date:s[1],number:parseInt(s[2],10),title:o,id:r,commit:a})}return t}import se from"fs";import Te from"path";import{execSync as hn}from"child_process";var tt=120;function Pe(e){if(!e)return"";let t=String(e).replace(/`([^`]*)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/^[-*+\s]+/,"").replace(/^#{1,6}\s*/,"").replace(/[*~]/g,"").replace(/\s+/g," ").trim().replace(/[::.\s]+$/,"");return t.length>tt&&(t=t.slice(0,tt-1).trimEnd()+"\u2026"),t}function Y(e){return String(e||"").toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function yn(e){if(!e||typeof e!="string")return[];let t=e.split(/\r?\n/),n=i=>i.map(l=>({text:Pe(l.titleRaw),body:l.bodyLines.join(`
50
+ `).trim()||null})).filter(l=>l.text),s=[],o=null;for(let i of t){let l=/^(#{1,6})\s+(.+?)\s*$/.exec(i);if(l&&l[1].length>=2&&l[1].length<=4){o&&s.push(o),o={titleRaw:l[2],bodyLines:[]};continue}o&&o.bodyLines.push(i)}o&&s.push(o);let r=[];o=null;for(let i of t){let l=/^(\d+)[.)]\s+(.+?)\s*$/.exec(i);if(l){o&&r.push(o),o={titleRaw:l[2],bodyLines:[]};continue}o&&o.bodyLines.push(i)}o&&r.push(o);let a=[n(s),n(r)].filter(i=>i.length>=2);if(a.length)return a.sort((i,l)=>l.length-i.length),a[0];let c=t.find(i=>i.trim());return[{text:Pe(c||"Plan")||"Plan",body:e.trim()||null}]}function gn(e){let t=[];return e.forEach((n,s)=>{t.push(`### Phase ${s+1}: ${n.text}`),n.body&&n.body.trim()&&t.push(n.body.trim()),t.push("")}),t.join(`
51
51
  `).replace(/\n{3,}/g,`
52
52
 
53
53
  `).trimEnd()+`
54
- `}function nt(e){let t=ce(),n=t.split(/\r?\n/),s=n.findIndex(i=>/^##\s+Phases\s*$/i.test(i)),o=gn(e);if(s===-1){let i=t.replace(/\s*$/,"");ne.writeFileSync(q(),`${i}
54
+ `}function nt(e){let t=de(),n=t.split(/\r?\n/),s=n.findIndex(i=>/^##\s+Phases\s*$/i.test(i)),o=gn(e);if(s===-1){let i=t.replace(/\s*$/,"");se.writeFileSync(q(),`${i}
55
55
 
56
56
  ## Phases
57
57
 
58
58
  ${o}`,"utf8");return}let r=n.length;for(let i=s+1;i<n.length;i++)if(/^##\s+/.test(n[i])&&!/^###/.test(n[i])){r=i;break}let a=n.slice(0,s+1).join(`
59
- `),l=n.slice(r).join(`
59
+ `),c=n.slice(r).join(`
60
60
  `).replace(/^\n+/,""),u=`
61
61
 
62
- ${o}${l.trim()?`
63
- `+l:""}`;ne.writeFileSync(q(),a+u,"utf8")}function st(e){let t=yn(e);if(t.length===0)return{added:[],skipped:[],total:0};let s=Ee()?[]:oe(ce()).map(u=>({text:u.text,body:u.body})),o=new Set(s.map(u=>Y(u.text))),r=[...s],a=[],l=[];for(let u of t){let i=Y(u.text);if(o.has(i)){l.push(u.text);continue}o.add(i),r.push(u),a.push(u.text)}return a.length>0&&nt(r),{added:a,skipped:l,total:r.length}}function _n(e){return e==="completed"?"done":e==="in_progress"?"in_progress":"open"}function Sn(e){try{return e.prepare("SELECT phase_id FROM main.roadmap_cursor WHERE singleton = 1").get()?.phase_id??null}catch{return null}}function ot(e,t){if(!Array.isArray(t)||t.length===0)return{changed:!1};let n=t.map(m=>({text:Oe(m.content||m.activeForm||""),status:_n(m.status)})).filter(m=>m.text);if(n.length===0)return{changed:!1};let s=e.prepare("SELECT id, status FROM main.roadmap_phases WHERE decision_name = ? AND parent_phase_id IS NULL").all(T).filter(m=>m.status!=="stale");if(s.length===0){let d=Ee()?[]:oe(ce()).map(w=>({text:w.text,body:w.body})),h=new Set(d.map(w=>Y(w.text))),f=[...d],g=0;for(let w of n){let b=Y(w.text);h.has(b)||(h.add(b),f.push({text:w.text,body:null}),g++)}if(g===0)return{changed:!1};nt(f);let _=te(e);return{changed:!0,seeded:g,diff:_}}let o=Sn(e);o==null&&(o=s.find(m=>m.status==="in_progress")?.id??s.find(m=>m.status==="open")?.id??s[0].id);let r=e.prepare("SELECT id, text, status FROM main.roadmap_phases WHERE parent_phase_id = ?").all(o),a=new Map(r.map(m=>[Y(m.text),m])),l=e.prepare("INSERT INTO main.roadmap_phases (decision_name, phase_number, parent_phase_id, text, status, position) VALUES (NULL, NULL, ?, ?, ?, ?)"),u=e.prepare("UPDATE main.roadmap_phases SET status = ? WHERE id = ?"),i=e.prepare("SELECT COALESCE(MAX(position), -1) + 1 AS n FROM main.roadmap_phases WHERE parent_phase_id = ?").get(o).n,c=0,p=0;for(let m of n){let d=a.get(Y(m.text));if(d){if(d.status==="done"&&m.status!=="done")continue;d.status!==m.status&&(u.run(m.status,d.id),p++)}else l.run(o,m.text,m.status,i++),c++}return{changed:c>0||p>0,parentId:o,inserted:c,updated:p}}var xn=new Set(["the","and","for","with","from","into","that","this","then","your","add","fix","update","make","phase","support","implement","feature","refactor","wire","wires","should","will","also","use","using","via"]);function wn(e){return[...new Set(Y(e).split(" ").filter(t=>t.length>=4&&!xn.has(t)))]}function bn(e,t){if(!e||!t?.length)return null;let n=String(e),s=/\bphase\s*#?\s*(\d+)\b/i.exec(n);if(s){let a=parseInt(s[1],10),l=t.find(u=>u.phase_number===a);if(l)return{...l,confidence:"high"}}let o=new Set(Y(n).split(" ").filter(Boolean)),r=null;for(let a of t){let l=wn(a.text);if(l.length<2)continue;let u=l.filter(c=>o.has(c)),i=u.length/l.length;u.length>=2&&i>=.6&&(!r||i>r.ratio)&&(r={...a,confidence:"medium",ratio:i})}return r?(delete r.ratio,r):null}function ve(e,t){return hn(`git ${t}`,{cwd:e,encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}function rt(e,t){let n=Re.join(t,".cairn"),s=Re.join(n,".last-commit"),o=Re.join(n,"roadmap-pending.json"),r;try{r=ve(t,"rev-parse HEAD")}catch{return{candidates:[],newCommits:0}}let a=null;try{a=ne.readFileSync(s,"utf8").trim()||null}catch{}let l=[];if(a&&a!==r)try{l=ve(t,`rev-list --no-merges --reverse ${a}..HEAD`).split(`
64
- `).filter(Boolean)}catch{l=[]}try{ne.writeFileSync(s,r,"utf8")}catch{}let u=[];try{let i=JSON.parse(ne.readFileSync(o,"utf8"));Array.isArray(i)&&(u=i)}catch{}if(l.length){let i=e.prepare("SELECT id, phase_number, text FROM main.roadmap_phases WHERE decision_name = ? AND parent_phase_id IS NULL AND status IN ('open','in_progress') AND phase_number IS NOT NULL").all(T);for(let c of l){let p="";try{p=ve(t,`show -s --format=%s%n%b ${c}`)}catch{}let m=bn(p,i);m&&!u.some(d=>d.phase_id===m.id)&&u.push({phase_id:m.id,phase_number:m.phase_number,text:m.text,commit:c.slice(0,7),confidence:m.confidence})}}if(u.length){let i=new Set(e.prepare("SELECT id FROM main.roadmap_phases WHERE status IN ('open','in_progress')").all().map(c=>c.id));u=u.filter(c=>i.has(c.phase_id))}try{ne.writeFileSync(o,JSON.stringify(u),"utf8")}catch{}return{candidates:u,newCommits:l.length}}import U from"fs";import P from"path";var le="cairn",X="roadmap/1",kn="<!-- slot:roadmap";function En(e){return`${kn} format=${X} provider=${le} generated=${e} -->`}var $n=`<!-- ${le}:roadmap -->`,Rn=/^<!--\s*slot:roadmap\b([^>]*?)-->/,vn=/^<!--\s*([A-Za-z0-9_.-]+)\s*:\s*roadmap\s*-->/,On=/([A-Za-z_][A-Za-z0-9_-]*)=("[^"]*"|\S+)/g;function jn(e){if(typeof e!="string")return null;let t=e.indexOf(`
65
- `);return(t===-1?e:e.slice(0,t)).trim()}function Tn(e){let t=jn(e);if(!t)return null;let n=Rn.exec(t);if(n){let o={};for(let r of n[1].matchAll(On))o[r[1]]=r[2].replace(/^"|"$/g,"");return o.provider?{provider:o.provider.toLowerCase(),format:o.format||null,generated:o.generated||null}:null}let s=vn.exec(t);return s?{provider:s[1].toLowerCase(),format:null,generated:null}:null}var Pn=/^```roadmap-json[ \t]*\r?\n([\s\S]*?)\r?\n```[ \t]*$/m;function ct(e){if(typeof e!="string")return null;let t=Pn.exec(e);if(!t)return null;try{let n=JSON.parse(t[1]);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}var Nn=new Set(["format","provider","generated","title","cursor","phases","migrated_from","migrated"]),Mn=new Set(["id","number","title","status","goal","blocked_by","slices","detail","links"]);function lt(e,t){let n={};if(!e||typeof e!="object")return n;for(let s of Object.keys(e).sort())t.has(s)||(n[s]=e[s]);return n}function ut(e,t=new Map){if(!Array.isArray(e))return t;for(let n of e)n&&typeof n=="object"&&typeof n.id=="string"&&(t.set(n.id,n),ut(n.slices,t));return t}function An(e){if(typeof e!="string")return null;let t=ct(e)?.migrated_from;if(typeof t=="string"&&t)return t;let n=e.indexOf(`
66
- `);if(n===-1)return null;let s=e.indexOf("-->",n),o=s===-1?e.slice(0,512):e.slice(n,s),r=/^\s*migrated-from=(.+?)\s*$/m.exec(o);return r?r[1]:null}var Fn=/\[\[([^\]|#\n]+?)(?:[|#][^\]\n]*)?\]\]/g,Ln=["decision","knowledge","experience","preference"];function Dn(e){let t=P.relative(z(),e).split(P.sep).join("/");return!t||t.startsWith("..")||P.isAbsolute(t)?null:t}function Cn(e){let t=P.join(z(),".cairn","memory");return[P.join(t,`${e}.md`),...Ln.map(n=>P.join(t,`${n}_${e}.md`))]}function In(e){if(!e)return[];let t=[],n=new Set;for(let s of String(e).matchAll(Fn)){let o=s[1].trim();if(!(!o||n.has(o))){n.add(o);for(let r of Cn(o)){if(!U.existsSync(r))continue;let a=Dn(r);a&&t.push({kind:"memory",title:o,path:a});break}}}return t}var Wn={open:"open",in_progress:"in progress",done:"done",blocked:"blocked",stale:"stale"},Un=new Set(["open","in_progress","done","blocked","stale"]);function Hn(e){return e==="done"?"x":e==="in_progress"?"~":e==="blocked"?"!":" "}function pt(){return P.join(z(),"ROADMAP.md")}function dt(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Jn(e){try{return e.prepare("SELECT phase_id FROM main.roadmap_cursor WHERE singleton = 1").get()?.phase_id??null}catch{return null}}function Bn(e){let t=new Map,n;try{n=e.prepare("SELECT blocker_id, blocked_id FROM main.roadmap_phase_deps").all()}catch{return t}for(let s of n)t.has(s.blocked_id)||t.set(s.blocked_id,new Set),t.get(s.blocked_id).add(s.blocker_id);return t}function Yn(e,t){let n=e.decision_name??"",s=t.decision_name??"";return n!==s?n<s?-1:1:e.phase_number!=null&&t.phase_number!=null?e.phase_number-t.phase_number:e.position-t.position||e.id-t.id}function zn(e){let t;try{t=e.prepare("SELECT id, decision_name, phase_number, parent_phase_id, text, body, status, position FROM main.roadmap_phases ORDER BY decision_name, phase_number, position, id").all()}catch{return null}if(t.filter(f=>f.status!=="stale").length===0)return null;let n=Jn(e),s=Bn(e),o=new Map(t.map(f=>[f.id,f.status])),r=new Map(t.map(f=>[f.id,f.phase_number!=null?`Phase ${f.phase_number}`:f.text])),a=new Map(t.map(f=>[f.id,f])),l=new Map;for(let f of t){let g=f.parent_phase_id??"root";l.has(g)||l.set(g,[]),l.get(g).push(f)}for(let f of l.values())f.sort(Yn);let u=new Map;for(let f of l.get("root")||[])f.decision_name!=null&&(f.decision_name===T&&f.phase_number==null||(u.has(f.decision_name)||u.set(f.decision_name,[]),u.get(f.decision_name).push(f)));let i=[...u.keys()].sort((f,g)=>f===T?-1:g===T?1:f<g?-1:f>g?1:0),c=new Map,p=!1;for(let f of i){let g=u.get(f).filter(w=>w.status!=="stale"),_=f===T?g.filter(w=>w.status!=="done"):g;_.length!==0&&(p=!0,c.set(f,{visible:_,doneCount:g.filter(w=>w.status==="done").length,total:g.length}))}return p?{cursor:n,decisionNames:i,visibleRoots:c,children:f=>(l.get(f)||[]).filter(g=>g.status!=="stale"),unfinishedBlockers:f=>{let g=s.get(f);return g?[...g].filter(_=>o.get(_)!=="done").map(_=>r.get(_)||`#${_}`):[]},blockerIds:f=>{let g=s.get(f);return g?[...g].filter(_=>a.has(_)).sort((_,w)=>_-w).map(_=>`phase-${_}`):[]}}:null}var je=120;function Gn(e){return e.replace(/\s*\((?:see\s+)?\[\[[^\]]+\]\](?:\s*(?:,|and)\s*\[\[[^\]]+\]\])*\s*\)/gi,"").replace(/\[\[([^\]]+)\]\]/g,(t,n)=>n.replace(/_/g," ").trim()).replace(/\s{2,}/g," ").replace(/\s+([.,;:!?])/g,"$1").trim()}function ft(e){if(!e)return null;let t=[];for(let a of e.split(`
67
- `)){let l=a.trim();if(!l){if(t.length)break;continue}t.push(l)}if(!t.length)return null;let n=Gn(t.join(" ").replace(/\s+/g," ")),s=null,o=/[.?!](?=\s|$)/g,r;for(;(r=o.exec(n))!==null&&(s=n.slice(0,r.index+1),!(s.length>=40)););if(s||(s=n),s.length>je){let a=s.lastIndexOf(" ",je-1);s=s.slice(0,a>60?a:je-1).trimEnd()+"\u2026"}return s}var Kn=8;function it(){let e=$e();if(!e||e.length===0)return[];let t=e.slice(-Kn).reverse(),n=["","---","","## Recently shipped",""];for(let o of t)n.push(`- ${o.date} \u2014 ${o.title}${o.commit?` \`${o.commit}\``:""}`);let s=e.length-t.length;return n.push("",s>0?`_${e.length} phases shipped in total; ${s} earlier one${s===1?"":"s"} not listed._`:`_${e.length} phase${e.length===1?"":"s"} shipped in total._`),n}function at(e){let t=e.doneCount,n=e.total;if(!n)return"_No phases yet._";let s=Math.round(t/n*10);return`**${t} of ${n} done** \`${"\u2588".repeat(s)}${"\u2591".repeat(10-s)}\``}function qn(e,t){let n=[En(t.generated),"<!--"," Generated by cairn \u2014 do NOT edit by hand."," The plan lives in .cairn/roadmap.md; status and cursor come from cairn_roadmap."," This file is regenerated whenever the roadmap changes; manual edits are overwritten."," Per-phase detail and links are in the roadmap-json block at the end of this file."];if(t.migratedFrom&&(n.push(" The ROADMAP.md that was here before cairn adopted this file is kept at:"),n.push(` migrated-from=${t.migratedFrom}`)),n.push("-->","","# Roadmap",""),e==null)return n.push("_No active plan right now._"),n.push(...it()),n;let{cursor:s,decisionNames:o,visibleRoots:r,children:a,unfinishedBlockers:l}=e;n.push("Legend: `[x]` done \xB7 `[~]` in progress \xB7 `[ ]` open \xB7 `[!]` blocked.");let u=(i,c)=>{let p=" ".repeat(c),m=i.phase_number!=null?`Phase ${i.phase_number}: ${i.text}`:i.text,d=Wn[i.status]||i.status,h=l(i.id);h.length&&(d+=` \xB7 waiting on ${h.join(", ")}`),s===i.id&&(d+=" \xB7 \u2190 current"),n.push(`${p}- [${Hn(i.status)}] **${m}** \u2014 ${d}`);let f=ft(i.body);f&&n.push(`${p} ${f}`);for(let g of a(i.id))u(g,c+1)};for(let i of o){let c=r.get(i);if(c){n.push(""),i===T?n.push("## Active plan","",at(c)):n.push(`## ${i}`,"",at(c)),n.push("");for(let p of c.visible)u(p,0)}}return n.push(...it()),n}function mt(e,t,n,s){let o=n.get(`phase-${e.id}`),r=ft(e.body),a=In(e.body),l=t.blockerIds(e.id),u={id:`phase-${e.id}`};if(e.phase_number!=null&&(u.number=e.phase_number),u.title=e.text,u.status=Un.has(e.status)?e.status:"open",r&&(u.goal=r),l.length&&(u.blocked_by=l),!s){let i=[],c=p=>{for(let m of t.children(p))i.push(mt(m,t,n,!0)),c(m.id)};c(e.id),i.length&&(u.slices=i)}return e.body&&e.body.trim()&&(u.detail=e.body.trim()),a.length&&(u.links=a),{...u,...lt(o,Mn)}}function Vn(e,t){let n=ut(t.previous?.phases),s=[];for(let a of e?.decisionNames??[]){let l=e.visibleRoots.get(a);if(l)for(let u of l.visible)s.push(mt(u,e,n,!1))}let o={format:X,provider:le,generated:t.generated,title:`${P.basename(z())} roadmap`,cursor:e?.cursor!=null?`phase-${e.cursor}`:null};t.migratedFrom&&(o.migrated_from=t.migratedFrom,t.migrated&&(o.migrated=t.migrated)),o.phases=s;let r={...o,...lt(t.previous,Nn)};return["","<details>","<summary>Machine-readable plan (roadmap/1)</summary>","","```roadmap-json",JSON.stringify(r,null,2),"```","","</details>"]}function Te(e,t={}){let n={generated:t.generated||dt(),migratedFrom:t.migratedFrom||null,migrated:t.migrated||null,previous:t.previous&&typeof t.previous=="object"?t.previous:null},s=zn(e);return s==null&&!t.allowEmpty?null:[...qn(s,n),...Vn(s,n)].join(`
62
+ ${o}${c.trim()?`
63
+ `+c:""}`;se.writeFileSync(q(),a+u,"utf8")}function st(e){let t=yn(e);if(t.length===0)return{added:[],skipped:[],total:0};let s=ve()?[]:ie(de()).map(u=>({text:u.text,body:u.body})),o=new Set(s.map(u=>Y(u.text))),r=[...s],a=[],c=[];for(let u of t){let i=Y(u.text);if(o.has(i)){c.push(u.text);continue}o.add(i),r.push(u),a.push(u.text)}return a.length>0&&nt(r),{added:a,skipped:c,total:r.length}}function _n(e){return e==="completed"?"done":e==="in_progress"?"in_progress":"open"}function Sn(e){try{return e.prepare("SELECT phase_id FROM main.roadmap_cursor WHERE singleton = 1").get()?.phase_id??null}catch{return null}}function ot(e,t){if(!Array.isArray(t)||t.length===0)return{changed:!1};let n=t.map(f=>({text:Pe(f.content||f.activeForm||""),status:_n(f.status)})).filter(f=>f.text);if(n.length===0)return{changed:!1};let s=e.prepare("SELECT id, status FROM main.roadmap_phases WHERE decision_name = ? AND parent_phase_id IS NULL").all(j).filter(f=>f.status!=="stale");if(s.length===0){let p=ve()?[]:ie(de()).map(S=>({text:S.text,body:S.body})),h=new Set(p.map(S=>Y(S.text))),m=[...p],_=0;for(let S of n){let b=Y(S.text);h.has(b)||(h.add(b),m.push({text:S.text,body:null}),_++)}if(_===0)return{changed:!1};nt(m);let g=ne(e);return{changed:!0,seeded:_,diff:g}}let o=Sn(e);o==null&&(o=s.find(f=>f.status==="in_progress")?.id??s.find(f=>f.status==="open")?.id??s[0].id);let r=e.prepare("SELECT id, text, status FROM main.roadmap_phases WHERE parent_phase_id = ?").all(o),a=new Map(r.map(f=>[Y(f.text),f])),c=e.prepare("INSERT INTO main.roadmap_phases (decision_name, phase_number, parent_phase_id, text, status, position) VALUES (NULL, NULL, ?, ?, ?, ?)"),u=e.prepare("UPDATE main.roadmap_phases SET status = ? WHERE id = ?"),i=e.prepare("SELECT COALESCE(MAX(position), -1) + 1 AS n FROM main.roadmap_phases WHERE parent_phase_id = ?").get(o).n,l=0,d=0;for(let f of n){let p=a.get(Y(f.text));if(p){if(p.status==="done"&&f.status!=="done")continue;p.status!==f.status&&(u.run(f.status,p.id),d++)}else c.run(o,f.text,f.status,i++),l++}return{changed:l>0||d>0,parentId:o,inserted:l,updated:d}}var xn=new Set(["the","and","for","with","from","into","that","this","then","your","add","fix","update","make","phase","support","implement","feature","refactor","wire","wires","should","will","also","use","using","via"]);function wn(e){return[...new Set(Y(e).split(" ").filter(t=>t.length>=4&&!xn.has(t)))]}function bn(e,t){if(!e||!t?.length)return null;let n=String(e),s=/\bphase\s*#?\s*(\d+)\b/i.exec(n);if(s){let a=parseInt(s[1],10),c=t.find(u=>u.phase_number===a);if(c)return{...c,confidence:"high"}}let o=new Set(Y(n).split(" ").filter(Boolean)),r=null;for(let a of t){let c=wn(a.text);if(c.length<2)continue;let u=c.filter(l=>o.has(l)),i=u.length/c.length;u.length>=2&&i>=.6&&(!r||i>r.ratio)&&(r={...a,confidence:"medium",ratio:i})}return r?(delete r.ratio,r):null}function je(e,t){return hn(`git ${t}`,{cwd:e,encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}function rt(e,t){let n=Te.join(t,".cairn"),s=Te.join(n,".last-commit"),o=Te.join(n,"roadmap-pending.json"),r;try{r=je(t,"rev-parse HEAD")}catch{return{candidates:[],newCommits:0}}let a=null;try{a=se.readFileSync(s,"utf8").trim()||null}catch{}let c=[];if(a&&a!==r)try{c=je(t,`rev-list --no-merges --reverse ${a}..HEAD`).split(`
64
+ `).filter(Boolean)}catch{c=[]}try{se.writeFileSync(s,r,"utf8")}catch{}let u=[];try{let i=JSON.parse(se.readFileSync(o,"utf8"));Array.isArray(i)&&(u=i)}catch{}if(c.length){let i=e.prepare("SELECT id, phase_number, text FROM main.roadmap_phases WHERE decision_name = ? AND parent_phase_id IS NULL AND status IN ('open','in_progress') AND phase_number IS NOT NULL").all(j);for(let l of c){let d="";try{d=je(t,`show -s --format=%s%n%b ${l}`)}catch{}let f=bn(d,i);f&&!u.some(p=>p.phase_id===f.id)&&u.push({phase_id:f.id,phase_number:f.phase_number,text:f.text,commit:l.slice(0,7),confidence:f.confidence})}}if(u.length){let i=new Set(e.prepare("SELECT id FROM main.roadmap_phases WHERE status IN ('open','in_progress')").all().map(l=>l.id));u=u.filter(l=>i.has(l.phase_id))}try{se.writeFileSync(o,JSON.stringify(u),"utf8")}catch{}return{candidates:u,newCommits:c.length}}import U from"fs";import P from"path";var pe="cairn",X="roadmap/1",kn="<!-- slot:roadmap";function En(e){return`${kn} format=${X} provider=${pe} generated=${e} -->`}var $n=`<!-- ${pe}:roadmap -->`,Rn=/^<!--\s*slot:roadmap\b([^>]*?)-->/,vn=/^<!--\s*([A-Za-z0-9_.-]+)\s*:\s*roadmap\s*-->/,On=/([A-Za-z_][A-Za-z0-9_-]*)=("[^"]*"|\S+)/g;function Tn(e){if(typeof e!="string")return null;let t=e.indexOf(`
65
+ `);return(t===-1?e:e.slice(0,t)).trim()}function jn(e){let t=Tn(e);if(!t)return null;let n=Rn.exec(t);if(n){let o={};for(let r of n[1].matchAll(On))o[r[1]]=r[2].replace(/^"|"$/g,"");return o.provider?{provider:o.provider.toLowerCase(),format:o.format||null,generated:o.generated||null}:null}let s=vn.exec(t);return s?{provider:s[1].toLowerCase(),format:null,generated:null}:null}var Pn=/^```roadmap-json[ \t]*\r?\n([\s\S]*?)\r?\n```[ \t]*$/m;function ct(e){if(typeof e!="string")return null;let t=Pn.exec(e);if(!t)return null;try{let n=JSON.parse(t[1]);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}var Nn=new Set(["format","provider","generated","title","cursor","phases","migrated_from","migrated"]),Mn=new Set(["id","number","title","status","goal","blocked_by","slices","detail","links"]);function lt(e,t){let n={};if(!e||typeof e!="object")return n;for(let s of Object.keys(e).sort())t.has(s)||(n[s]=e[s]);return n}function ut(e,t=new Map){if(!Array.isArray(e))return t;for(let n of e)n&&typeof n=="object"&&typeof n.id=="string"&&(t.set(n.id,n),ut(n.slices,t));return t}function An(e){if(typeof e!="string")return null;let t=ct(e)?.migrated_from;if(typeof t=="string"&&t)return t;let n=e.indexOf(`
66
+ `);if(n===-1)return null;let s=e.indexOf("-->",n),o=s===-1?e.slice(0,512):e.slice(n,s),r=/^\s*migrated-from=(.+?)\s*$/m.exec(o);return r?r[1]:null}var Fn=/\[\[([^\]|#\n]+?)(?:[|#][^\]\n]*)?\]\]/g,Ln=["decision","knowledge","experience","preference"];function Dn(e){let t=P.relative(z(),e).split(P.sep).join("/");return!t||t.startsWith("..")||P.isAbsolute(t)?null:t}function Cn(e){let t=P.join(z(),".cairn","memory");return[P.join(t,`${e}.md`),...Ln.map(n=>P.join(t,`${n}_${e}.md`))]}function In(e){if(!e)return[];let t=[],n=new Set;for(let s of String(e).matchAll(Fn)){let o=s[1].trim();if(!(!o||n.has(o))){n.add(o);for(let r of Cn(o)){if(!U.existsSync(r))continue;let a=Dn(r);a&&t.push({kind:"memory",title:o,path:a});break}}}return t}var Wn={open:"open",in_progress:"in progress",done:"done",blocked:"blocked",stale:"stale"},Un=new Set(["open","in_progress","done","blocked","stale"]);function Hn(e){return e==="done"?"x":e==="in_progress"?"~":e==="blocked"?"!":" "}function dt(){return P.join(z(),"ROADMAP.md")}function pt(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Jn(e){try{return e.prepare("SELECT phase_id FROM main.roadmap_cursor WHERE singleton = 1").get()?.phase_id??null}catch{return null}}function Bn(e){let t=new Map,n;try{n=e.prepare("SELECT blocker_id, blocked_id FROM main.roadmap_phase_deps").all()}catch{return t}for(let s of n)t.has(s.blocked_id)||t.set(s.blocked_id,new Set),t.get(s.blocked_id).add(s.blocker_id);return t}function Yn(e,t){let n=e.decision_name??"",s=t.decision_name??"";return n!==s?n<s?-1:1:e.phase_number!=null&&t.phase_number!=null?e.phase_number-t.phase_number:e.position-t.position||e.id-t.id}function zn(e){let t;try{t=e.prepare("SELECT id, decision_name, phase_number, parent_phase_id, text, body, status, position FROM main.roadmap_phases ORDER BY decision_name, phase_number, position, id").all()}catch{return null}if(t.filter(m=>m.status!=="stale").length===0)return null;let n=Jn(e),s=Bn(e),o=new Map(t.map(m=>[m.id,m.status])),r=new Map(t.map(m=>[m.id,m.phase_number!=null?`Phase ${m.phase_number}`:m.text])),a=new Map(t.map(m=>[m.id,m])),c=new Map;for(let m of t){let _=m.parent_phase_id??"root";c.has(_)||c.set(_,[]),c.get(_).push(m)}for(let m of c.values())m.sort(Yn);let u=new Map;for(let m of c.get("root")||[])m.decision_name!=null&&(m.decision_name===j&&m.phase_number==null||(u.has(m.decision_name)||u.set(m.decision_name,[]),u.get(m.decision_name).push(m)));let i=[...u.keys()].sort((m,_)=>m===j?-1:_===j?1:m<_?-1:m>_?1:0),l=new Map,d=!1;for(let m of i){let _=u.get(m).filter(S=>S.status!=="stale"),g=m===j?_.filter(S=>S.status!=="done"):_;g.length!==0&&(d=!0,l.set(m,{visible:g,doneCount:_.filter(S=>S.status==="done").length,total:_.length}))}return d?{cursor:n,decisionNames:i,visibleRoots:l,children:m=>(c.get(m)||[]).filter(_=>_.status!=="stale"),unfinishedBlockers:m=>{let _=s.get(m);return _?[..._].filter(g=>o.get(g)!=="done").map(g=>r.get(g)||`#${g}`):[]},blockerIds:m=>{let _=s.get(m);return _?[..._].filter(g=>a.has(g)).sort((g,S)=>g-S).map(g=>`phase-${g}`):[]}}:null}var Ne=120;function Gn(e){return e.replace(/\s*\((?:see\s+)?\[\[[^\]]+\]\](?:\s*(?:,|and)\s*\[\[[^\]]+\]\])*\s*\)/gi,"").replace(/\[\[([^\]]+)\]\]/g,(t,n)=>n.replace(/_/g," ").trim()).replace(/\s{2,}/g," ").replace(/\s+([.,;:!?])/g,"$1").trim()}function ft(e){if(!e)return null;let t=[];for(let a of e.split(`
67
+ `)){let c=a.trim();if(!c){if(t.length)break;continue}t.push(c)}if(!t.length)return null;let n=Gn(t.join(" ").replace(/\s+/g," ")),s=null,o=/[.?!](?=\s|$)/g,r;for(;(r=o.exec(n))!==null&&(s=n.slice(0,r.index+1),!(s.length>=40)););if(s||(s=n),s.length>Ne){let a=s.lastIndexOf(" ",Ne-1);s=s.slice(0,a>60?a:Ne-1).trimEnd()+"\u2026"}return s}var Kn=8;function it(){let e=Oe();if(!e||e.length===0)return[];let t=e.slice(-Kn).reverse(),n=["","---","","## Recently shipped",""];for(let o of t)n.push(`- ${o.date} \u2014 ${o.title}${o.commit?` \`${o.commit}\``:""}`);let s=e.length-t.length;return n.push("",s>0?`_${e.length} phases shipped in total; ${s} earlier one${s===1?"":"s"} not listed._`:`_${e.length} phase${e.length===1?"":"s"} shipped in total._`),n}function at(e){let t=e.doneCount,n=e.total;if(!n)return"_No phases yet._";let s=Math.round(t/n*10);return`**${t} of ${n} done** \`${"\u2588".repeat(s)}${"\u2591".repeat(10-s)}\``}function qn(e,t){let n=[En(t.generated),"<!--"," Generated by cairn \u2014 do NOT edit by hand."," The plan lives in .cairn/roadmap.md; status and cursor come from cairn_roadmap."," This file is regenerated whenever the roadmap changes; manual edits are overwritten."," Per-phase detail and links are in the roadmap-json block at the end of this file."];if(t.migratedFrom&&(n.push(" The ROADMAP.md that was here before cairn adopted this file is kept at:"),n.push(` migrated-from=${t.migratedFrom}`)),n.push("-->","","# Roadmap",""),e==null)return n.push("_No active plan right now._"),n.push(...it()),n;let{cursor:s,decisionNames:o,visibleRoots:r,children:a,unfinishedBlockers:c}=e;n.push("Legend: `[x]` done \xB7 `[~]` in progress \xB7 `[ ]` open \xB7 `[!]` blocked.");let u=(i,l)=>{let d=" ".repeat(l),f=i.phase_number!=null?`Phase ${i.phase_number}: ${i.text}`:i.text,p=Wn[i.status]||i.status,h=c(i.id);h.length&&(p+=` \xB7 waiting on ${h.join(", ")}`),s===i.id&&(p+=" \xB7 \u2190 current"),n.push(`${d}- [${Hn(i.status)}] **${f}** \u2014 ${p}`);let m=ft(i.body);m&&n.push(`${d} ${m}`);for(let _ of a(i.id))u(_,l+1)};for(let i of o){let l=r.get(i);if(l){n.push(""),i===j?n.push("## Active plan","",at(l)):n.push(`## ${i}`,"",at(l)),n.push("");for(let d of l.visible)u(d,0)}}return n.push(...it()),n}function mt(e,t,n,s){let o=n.get(`phase-${e.id}`),r=ft(e.body),a=In(e.body),c=t.blockerIds(e.id),u={id:`phase-${e.id}`};if(e.phase_number!=null&&(u.number=e.phase_number),u.title=e.text,u.status=Un.has(e.status)?e.status:"open",r&&(u.goal=r),c.length&&(u.blocked_by=c),!s){let i=[],l=d=>{for(let f of t.children(d))i.push(mt(f,t,n,!0)),l(f.id)};l(e.id),i.length&&(u.slices=i)}return e.body&&e.body.trim()&&(u.detail=e.body.trim()),a.length&&(u.links=a),{...u,...lt(o,Mn)}}function Vn(e,t){let n=ut(t.previous?.phases),s=[];for(let a of e?.decisionNames??[]){let c=e.visibleRoots.get(a);if(c)for(let u of c.visible)s.push(mt(u,e,n,!1))}let o={format:X,provider:pe,generated:t.generated,title:`${P.basename(z())} roadmap`,cursor:e?.cursor!=null?`phase-${e.cursor}`:null};t.migratedFrom&&(o.migrated_from=t.migratedFrom,t.migrated&&(o.migrated=t.migrated)),o.phases=s;let r={...o,...lt(t.previous,Nn)};return["","<details>","<summary>Machine-readable plan (roadmap/1)</summary>","","```roadmap-json",JSON.stringify(r,null,2),"```","","</details>"]}function Me(e,t={}){let n={generated:t.generated||pt(),migratedFrom:t.migratedFrom||null,migrated:t.migrated||null,previous:t.previous&&typeof t.previous=="object"?t.previous:null},s=zn(e);return s==null&&!t.allowEmpty?null:[...qn(s,n),...Vn(s,n)].join(`
68
68
  `)+`
69
- `}function Xn(e){let t=P.join(e,"ROADMAP.bak.md");if(!U.existsSync(t))return t;for(let n=2;n<=1e3;n++){let s=P.join(e,`ROADMAP.bak.${n}.md`);if(!U.existsSync(s))return s}return null}function Zn(e,t){let n=P.join(P.dirname(e),`.${P.basename(e)}.${process.pid}.tmp`);try{U.writeFileSync(n,t,"utf8"),U.renameSync(n,e)}catch(s){try{U.unlinkSync(n)}catch{}throw s}}function V(e,t,n={}){return{written:!1,reason:e,warning:`[cairn] ROADMAP.md was not updated \u2014 ${e}`,path:t,...n}}function ht(e){let t=pt(),n=null;if(U.existsSync(t))try{n=U.readFileSync(t,"utf8")}catch(f){return V(`the existing file could not be read (${f.message})`,t)}let s=Tn(n),o=n!=null&&(s?.provider===le||n.startsWith($n));if(n!=null&&s&&!o)return{written:!1,reason:`ROADMAP.md is generated by another provider (${s.provider}) \u2014 refusing to overwrite`,conflict_provider:s.provider,warning:`[cairn] ROADMAP.md is published by "${s.provider}", so cairn left it untouched and the file may not reflect cairn's plan. Two roadmap providers are claiming the same file \u2014 decide which one owns it.`,path:t};let r=o?ct(n):null,a=o?An(n):null,l=o&&typeof r?.migrated=="string"?r.migrated:null,u=typeof r?.generated=="string"?r.generated:null,i=!1,c=Te(e,{generated:u||"1970-01-01T00:00:00Z",migratedFrom:a,migrated:l,previous:r});if(c==null){if(!o)return{written:!1,reason:"empty roadmap \u2014 no file written",path:t};i=!0,c=Te(e,{generated:u||"1970-01-01T00:00:00Z",migratedFrom:a,migrated:l,previous:r,allowEmpty:!0})}if(o&&n===c)return{written:!1,unchanged:!0,path:t,bytes:Buffer.byteLength(c)};let p=dt(),m=null,d=null;if(n!=null&&!o){let f=Xn(P.dirname(t));if(f==null)return V("no free ROADMAP.bak name was available to preserve the existing file",t);try{U.renameSync(t,f)}catch(g){return V(`the existing file could not be preserved (${g.message})`,t)}m=P.basename(f),d=f,a=m,l=p}c=Te(e,{generated:p,migratedFrom:a,migrated:l,previous:r,allowEmpty:i});try{Zn(t,c)}catch(f){if(d)try{return U.renameSync(d,t),V(`write failed (${f.message}); the original ROADMAP.md was restored`,t)}catch{return V(`write failed (${f.message}); the original ROADMAP.md is at ${m} and must be restored by hand`,t,{backed_up_to:m})}return V(`write failed (${f.message})`,t)}let h={written:!0,path:t,bytes:Buffer.byteLength(c),format:X,generated:p};return m&&(h.backed_up_to=m,h.warning=`[cairn] The existing ROADMAP.md was not cairn-generated. It has been preserved as ${m}, and ROADMAP.md is now generated from cairn's roadmap.`),h}function Qn(e){try{return ht(e)}catch(t){process.stderr.write(`[cairn] ROADMAP.md publish skipped: ${t.message}
70
- `);let n=null;try{n=pt()}catch{}return V(`publish failed (${t.message})`,n)}}function ue(e){let t=Qn(e);return t&&t.warning?t.warning:null}var es=new Set(["open","in_progress"]);function ts(e,t){e.prepare("INSERT INTO main.roadmap_cursor (singleton, phase_id) VALUES (1, ?) ON CONFLICT(singleton) DO UPDATE SET phase_id = excluded.phase_id").run(t)}function ns(e,t){let n=e.prepare("SELECT parent_phase_id, status FROM main.roadmap_phases WHERE id = ?"),s=e.prepare("UPDATE main.roadmap_phases SET status = 'in_progress' WHERE id = ? AND status = 'open'"),o=n.get(t);for(;o&&o.parent_phase_id!=null;)s.run(o.parent_phase_id),o=n.get(o.parent_phase_id)}function yt(e,t){ts(e,t),e.prepare("UPDATE main.roadmap_phases SET status = 'in_progress' WHERE id = ? AND status = 'open'").run(t),ns(e,t)}function ss(e){let t=new Map,n;try{n=e.prepare("SELECT blocker_id, blocked_id FROM main.roadmap_phase_deps").all()}catch{return t}for(let s of n)t.has(s.blocked_id)||t.set(s.blocked_id,new Set),t.get(s.blocked_id).add(s.blocker_id);return t}function os(e,t,n){let s=t.get(e);if(!s||s.size===0)return[];let o=[];for(let r of s)n.get(r)!=="done"&&o.push(r);return o}function gt(e,t){let n=e.prepare("SELECT id, decision_name, phase_number, parent_phase_id, status, position, text FROM main.roadmap_phases ORDER BY decision_name, phase_number, position, id").all();if(n.length===0)return{id:null,reason:"No phases \u2014 add a ## Phases section to .cairn/roadmap.md."};let s=new Map(n.map(p=>[p.id,p.status])),o=ss(e),r=new Map;for(let p of n){let m=p.parent_phase_id??`root:${p.decision_name}`;r.has(m)||r.set(m,[]),r.get(m).push(p)}for(let p of r.values())p.sort((m,d)=>m.phase_number!=null&&d.phase_number!=null?m.phase_number-d.phase_number:m.position-d.position||m.id-d.id);let a=[],l=new Set;for(let p of n){if(p.parent_phase_id!=null||l.has(p.decision_name))continue;l.add(p.decision_name);let m=[],d=r.get(`root:${p.decision_name}`)||[];for(let h=d.length-1;h>=0;h--)m.push(d[h]);for(;m.length;){let h=m.pop();a.push(h);let f=r.get(h.id)||[];for(let g=f.length-1;g>=0;g--)m.push(f[g])}}let u=p=>es.has(p.status),i=[],c=0;if(t!=null){let p=a.findIndex(m=>m.id===t);c=p===-1?0:p+1}for(let p=c;p<a.length;p++){let m=a[p];if(!u(m))continue;let d=os(m.id,o,s);if(d.length>0){i.push({id:m.id,blockers:d});continue}let h=t!=null?n.find(_=>_.id===t):null,f=h&&h.decision_name!==m.decision_name,g;return t==null?g=`First actionable phase: ${m.decision_name??"(sub-task)"} / Phase ${m.phase_number??"\xB7"}.`:f?g=`Previous decision "${h.decision_name}" is complete \u2014 advanced to "${m.decision_name}".`:g=`Next open phase in "${m.decision_name??"(sub-task)"}" after id ${t}.`,i.length>0&&(g+=` Skipped ${i.length} dep-blocked phase(s): ${i.map(_=>`id ${_.id} (blocked by ${_.blockers.join(",")})`).join("; ")}.`),{id:m.id,reason:g,skipped_blocked:i}}return i.length>0?{id:null,reason:`All remaining open phases are blocked by unfinished dependencies: ${i.map(p=>`id ${p.id} (blocked by ${p.blockers.join(",")})`).join("; ")}.`,skipped_blocked:i}:{id:null,reason:"No actionable phases remaining."}}var is=new Set(["java","typescript","javascript","vue","python","sql"]);function Pe(e,t){let n={hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e};t&&(n.additionalContext=t),process.stdout.write(JSON.stringify({decision:"block",reason:e,hookSpecificOutput:n})),process.exit(0)}var wt={name:"cairn",contract:1,title:"cairn",slots:["roadmap"],provides:{roadmap:{path:"ROADMAP.md",format:X}},spec:"Project memory and roadmap. Publishes the plan as ROADMAP.md in the roadmap/1 slot format."};function as(){let e=S.join(Z.homedir(),".claude.json");if(!y.existsSync(e))return!1;let t;try{t=JSON.parse(y.readFileSync(e,"utf8"))}catch{return!1}let n=t?.mcpServers?.cairn;if(!n||typeof n!="object")return!1;let s=n.terminalConnect,o=s?.provides?.roadmap?.format;if(s&&o===X)return!1;n.terminalConnect=wt;try{return y.writeFileSync(e,JSON.stringify(t,null,2),"utf8"),!0}catch{return!1}}function bt(e){let t=S.join(Z.homedir(),".claude","projects",me(e));return y.existsSync(t)?S.join(t,"memory"):null}function kt(e){try{return y.readdirSync(e).filter(t=>t.endsWith(".md"))}catch{return[]}}function cs(e){let t=bt(e);if(!t||!y.existsSync(t))return 0;let n=S.join(e,".cairn","memory");y.mkdirSync(n,{recursive:!0});let s=0;for(let o of kt(t)){let r=S.join(t,o),a;try{a=y.statSync(r)}catch{continue}if(!a.isFile())continue;let l=S.join(n,o),u=!y.existsSync(l);if(!u)try{u=a.mtimeMs>y.statSync(l).mtimeMs}catch{u=!0}if(u){y.copyFileSync(r,l);try{y.utimesSync(l,a.atime,a.mtime)}catch{}s++}}return s}function ls(e){let t=bt(e);if(!t||(y.mkdirSync(t,{recursive:!0}),kt(t).some(o=>o!=="MEMORY.md")))return 0;let n=S.join(e,".cairn","memory");if(!y.existsSync(n))return 0;let s=0;for(let o of y.readdirSync(n)){let r=S.join(n,o),a;try{a=y.statSync(r)}catch{continue}if(a.isFile()){y.copyFileSync(r,S.join(t,o));try{y.utimesSync(S.join(t,o),a.atime,a.mtime)}catch{}s++}}return s}function _t(e,t){let n=new Date(t.checkpoint_at).toLocaleString(),r=[` message: ${/^Auto-checkpoint\b/.test(t.message||"")&&t.last_manual_message||t.message}`];r.push(` would_lose: ${Se(se(e,t))}`),r.push(` checkpoint: ${n}`),t.active_files?.length>0&&r.push(` active_files: ${t.active_files.join(", ")}`),t.notes?.length>0&&r.push(` notes: ${t.notes.join(" | ")}`);let a=i=>{try{return rs(i,{cwd:e,encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}};try{let i=new Date(t.checkpoint_at).toISOString(),c=a(`git log --oneline --after="${i}"`);c!==null&&r.push(` commits_since: ${c?c.split(`
71
- `).join("; "):"(none)"}`)}catch{}let l=a("git diff --name-only HEAD");l&&r.push(` uncommitted: ${l.split(`
69
+ `}function Xn(e){let t=P.join(e,"ROADMAP.bak.md");if(!U.existsSync(t))return t;for(let n=2;n<=1e3;n++){let s=P.join(e,`ROADMAP.bak.${n}.md`);if(!U.existsSync(s))return s}return null}function Zn(e,t){let n=P.join(P.dirname(e),`.${P.basename(e)}.${process.pid}.tmp`);try{U.writeFileSync(n,t,"utf8"),U.renameSync(n,e)}catch(s){try{U.unlinkSync(n)}catch{}throw s}}function V(e,t,n={}){return{written:!1,reason:e,warning:`[cairn] ROADMAP.md was not updated \u2014 ${e}`,path:t,...n}}function ht(e){let t=dt(),n=null;if(U.existsSync(t))try{n=U.readFileSync(t,"utf8")}catch(m){return V(`the existing file could not be read (${m.message})`,t)}let s=jn(n),o=n!=null&&(s?.provider===pe||n.startsWith($n));if(n!=null&&s&&!o)return{written:!1,reason:`ROADMAP.md is generated by another provider (${s.provider}) \u2014 refusing to overwrite`,conflict_provider:s.provider,warning:`[cairn] ROADMAP.md is published by "${s.provider}", so cairn left it untouched and the file may not reflect cairn's plan. Two roadmap providers are claiming the same file \u2014 decide which one owns it.`,path:t};let r=o?ct(n):null,a=o?An(n):null,c=o&&typeof r?.migrated=="string"?r.migrated:null,u=typeof r?.generated=="string"?r.generated:null,i=!1,l=Me(e,{generated:u||"1970-01-01T00:00:00Z",migratedFrom:a,migrated:c,previous:r});if(l==null){if(!o)return{written:!1,reason:"empty roadmap \u2014 no file written",path:t};i=!0,l=Me(e,{generated:u||"1970-01-01T00:00:00Z",migratedFrom:a,migrated:c,previous:r,allowEmpty:!0})}if(o&&n===l)return{written:!1,unchanged:!0,path:t,bytes:Buffer.byteLength(l)};let d=pt(),f=null,p=null;if(n!=null&&!o){let m=Xn(P.dirname(t));if(m==null)return V("no free ROADMAP.bak name was available to preserve the existing file",t);try{U.renameSync(t,m)}catch(_){return V(`the existing file could not be preserved (${_.message})`,t)}f=P.basename(m),p=m,a=f,c=d}l=Me(e,{generated:d,migratedFrom:a,migrated:c,previous:r,allowEmpty:i});try{Zn(t,l)}catch(m){if(p)try{return U.renameSync(p,t),V(`write failed (${m.message}); the original ROADMAP.md was restored`,t)}catch{return V(`write failed (${m.message}); the original ROADMAP.md is at ${f} and must be restored by hand`,t,{backed_up_to:f})}return V(`write failed (${m.message})`,t)}let h={written:!0,path:t,bytes:Buffer.byteLength(l),format:X,generated:d};return f&&(h.backed_up_to=f,h.warning=`[cairn] The existing ROADMAP.md was not cairn-generated. It has been preserved as ${f}, and ROADMAP.md is now generated from cairn's roadmap.`),h}function Qn(e){try{return ht(e)}catch(t){process.stderr.write(`[cairn] ROADMAP.md publish skipped: ${t.message}
70
+ `);let n=null;try{n=dt()}catch{}return V(`publish failed (${t.message})`,n)}}function fe(e){let t=Qn(e);return t&&t.warning?t.warning:null}var es=new Set(["open","in_progress"]);function ts(e,t){e.prepare("INSERT INTO main.roadmap_cursor (singleton, phase_id) VALUES (1, ?) ON CONFLICT(singleton) DO UPDATE SET phase_id = excluded.phase_id").run(t)}function ns(e,t){let n=e.prepare("SELECT parent_phase_id, status FROM main.roadmap_phases WHERE id = ?"),s=e.prepare("UPDATE main.roadmap_phases SET status = 'in_progress' WHERE id = ? AND status = 'open'"),o=n.get(t);for(;o&&o.parent_phase_id!=null;)s.run(o.parent_phase_id),o=n.get(o.parent_phase_id)}function yt(e,t){ts(e,t),e.prepare("UPDATE main.roadmap_phases SET status = 'in_progress' WHERE id = ? AND status = 'open'").run(t),ns(e,t)}function ss(e){let t=new Map,n;try{n=e.prepare("SELECT blocker_id, blocked_id FROM main.roadmap_phase_deps").all()}catch{return t}for(let s of n)t.has(s.blocked_id)||t.set(s.blocked_id,new Set),t.get(s.blocked_id).add(s.blocker_id);return t}function os(e,t,n){let s=t.get(e);if(!s||s.size===0)return[];let o=[];for(let r of s)n.get(r)!=="done"&&o.push(r);return o}function gt(e,t){let n=e.prepare("SELECT id, decision_name, phase_number, parent_phase_id, status, position, text FROM main.roadmap_phases ORDER BY decision_name, phase_number, position, id").all();if(n.length===0)return{id:null,reason:"No phases \u2014 add a ## Phases section to .cairn/roadmap.md."};let s=new Map(n.map(d=>[d.id,d.status])),o=ss(e),r=new Map;for(let d of n){let f=d.parent_phase_id??`root:${d.decision_name}`;r.has(f)||r.set(f,[]),r.get(f).push(d)}for(let d of r.values())d.sort((f,p)=>f.phase_number!=null&&p.phase_number!=null?f.phase_number-p.phase_number:f.position-p.position||f.id-p.id);let a=[],c=new Set;for(let d of n){if(d.parent_phase_id!=null||c.has(d.decision_name))continue;c.add(d.decision_name);let f=[],p=r.get(`root:${d.decision_name}`)||[];for(let h=p.length-1;h>=0;h--)f.push(p[h]);for(;f.length;){let h=f.pop();a.push(h);let m=r.get(h.id)||[];for(let _=m.length-1;_>=0;_--)f.push(m[_])}}let u=d=>es.has(d.status),i=[],l=0;if(t!=null){let d=a.findIndex(f=>f.id===t);l=d===-1?0:d+1}for(let d=l;d<a.length;d++){let f=a[d];if(!u(f))continue;let p=os(f.id,o,s);if(p.length>0){i.push({id:f.id,blockers:p});continue}let h=t!=null?n.find(g=>g.id===t):null,m=h&&h.decision_name!==f.decision_name,_;return t==null?_=`First actionable phase: ${f.decision_name??"(sub-task)"} / Phase ${f.phase_number??"\xB7"}.`:m?_=`Previous decision "${h.decision_name}" is complete \u2014 advanced to "${f.decision_name}".`:_=`Next open phase in "${f.decision_name??"(sub-task)"}" after id ${t}.`,i.length>0&&(_+=` Skipped ${i.length} dep-blocked phase(s): ${i.map(g=>`id ${g.id} (blocked by ${g.blockers.join(",")})`).join("; ")}.`),{id:f.id,reason:_,skipped_blocked:i}}return i.length>0?{id:null,reason:`All remaining open phases are blocked by unfinished dependencies: ${i.map(d=>`id ${d.id} (blocked by ${d.blockers.join(",")})`).join("; ")}.`,skipped_blocked:i}:{id:null,reason:"No actionable phases remaining."}}var is=new Set(["java","typescript","javascript","vue","python","sql"]);function ae(e,t){let n={hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e};t&&(n.additionalContext=t),process.stdout.write(JSON.stringify({decision:"block",reason:e,hookSpecificOutput:n})),process.exit(0)}var wt={name:"cairn",contract:1,title:"cairn",slots:["roadmap"],provides:{roadmap:{path:"ROADMAP.md",format:X}},spec:"Project memory and roadmap. Publishes the plan as ROADMAP.md in the roadmap/1 slot format."};function as(){let e=x.join(Z.homedir(),".claude.json");if(!y.existsSync(e))return!1;let t;try{t=JSON.parse(y.readFileSync(e,"utf8"))}catch{return!1}let n=t?.mcpServers?.cairn;if(!n||typeof n!="object")return!1;let s=n.terminalConnect,o=s?.provides?.roadmap?.format;if(s&&o===X)return!1;n.terminalConnect=wt;try{return y.writeFileSync(e,JSON.stringify(t,null,2),"utf8"),!0}catch{return!1}}function bt(e){let t=x.join(Z.homedir(),".claude","projects",ge(e));return y.existsSync(t)?x.join(t,"memory"):null}function kt(e){try{return y.readdirSync(e).filter(t=>t.endsWith(".md"))}catch{return[]}}function cs(e){let t=bt(e);if(!t||!y.existsSync(t))return 0;let n=x.join(e,".cairn","memory");y.mkdirSync(n,{recursive:!0});let s=0;for(let o of kt(t)){let r=x.join(t,o),a;try{a=y.statSync(r)}catch{continue}if(!a.isFile())continue;let c=x.join(n,o),u=!y.existsSync(c);if(!u)try{u=a.mtimeMs>y.statSync(c).mtimeMs}catch{u=!0}if(u){y.copyFileSync(r,c);try{y.utimesSync(c,a.atime,a.mtime)}catch{}s++}}return s}function ls(e){let t=bt(e);if(!t||(y.mkdirSync(t,{recursive:!0}),kt(t).some(o=>o!=="MEMORY.md")))return 0;let n=x.join(e,".cairn","memory");if(!y.existsSync(n))return 0;let s=0;for(let o of y.readdirSync(n)){let r=x.join(n,o),a;try{a=y.statSync(r)}catch{continue}if(a.isFile()){y.copyFileSync(r,x.join(t,o));try{y.utimesSync(x.join(t,o),a.atime,a.mtime)}catch{}s++}}return s}function _t(e,t){let n=new Date(t.checkpoint_at).toLocaleString(),r=[` message: ${/^Auto-checkpoint\b/.test(t.message||"")&&t.last_manual_message||t.message}`];r.push(` would_lose: ${be(re(e,t))}`),r.push(` checkpoint: ${n}`),t.active_files?.length>0&&r.push(` active_files: ${t.active_files.join(", ")}`),t.notes?.length>0&&r.push(` notes: ${t.notes.join(" | ")}`);let a=i=>{try{return rs(i,{cwd:e,encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}};try{let i=new Date(t.checkpoint_at).toISOString(),l=a(`git log --oneline --after="${i}"`);l!==null&&r.push(` commits_since: ${l?l.split(`
71
+ `).join("; "):"(none)"}`)}catch{}let c=a("git diff --name-only HEAD");c&&r.push(` uncommitted: ${c.split(`
72
72
  `).join(", ")}`);let u=a("git status --short");return u&&r.push(` git_status:
73
73
  ${u.split(`
74
74
  `).map(i=>" "+i).join(`
75
- `)}`),r.push(" \u2192 Call cairn_resume for full index status and open todos."),r}async function St(e){let t={active:!1},n=S.join(e,"index.db");if(!y.existsSync(n))return t;let s;try{({DatabaseSync:s}=await import("node:sqlite"))}catch{return t}let o;try{o=new s(n,{readonly:!0})}catch{return t}let r=l=>l.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");function a(l,u){if(!y.existsSync(l))return null;let i=y.readFileSync(l,"utf8"),c=!1,p=!1,m=[];for(let d of i.split(/\r?\n/)){if(/^##\s+Phases\s*$/i.test(d)){c=!0;continue}if(c&&/^##\s+/.test(d)&&!/^###/.test(d))break;if(!c)continue;let h=/^###\s+Phase\s+(\d+)\s*:\s*(.+?)\s*$/.exec(d);if(h){if(p)break;parseInt(h[1],10)===u&&(m.push(`### Phase ${h[1]}: ${h[2]}`),p=!0);continue}p&&m.push(d)}return m.join(`
76
- `).trim()||null}try{let u=o.prepare("SELECT phase_id FROM roadmap_cursor WHERE singleton = 1").get()?.phase_id??null;if(u==null)return o.close(),t;let i=o.prepare("SELECT id, decision_name, phase_number, parent_phase_id, text, status, position FROM roadmap_phases ORDER BY decision_name, phase_number, position, id").all(),c={open:"[ ]",in_progress:"[~]",done:"[x]",blocked:"[!]",stale:"[s]"},p=new Map;for(let R of i){let E=R.parent_phase_id??"root";p.has(E)||p.set(E,[]),p.get(E).push(R)}for(let R of p.values())R.sort((E,$)=>E.decision_name&&$.decision_name&&E.decision_name!==$.decision_name?E.decision_name.localeCompare($.decision_name):E.phase_number!=null&&$.phase_number!=null?E.phase_number-$.phase_number:E.position-$.position||E.id-$.id);let m=p.get("root")||[],d=new Map;for(let R of m)R.decision_name!=null&&(d.has(R.decision_name)||d.set(R.decision_name,[]),d.get(R.decision_name).push(R));let h=[],f=(R,E)=>{for(let $ of p.get(R)||[]){if($.status==="stale")continue;let pe=u===$.id?" \u2192":"",de=$.phase_number!=null?`Phase ${$.phase_number}: ${$.text}`:$.text;h.push(`${" ".repeat(E)}${c[$.status]||"[?]"}${pe} ${de}`),f($.id,E+1)}};for(let[R,E]of d){let $=E.filter(j=>j.status!=="stale");if($.length===0)continue;let pe=$.every(j=>j.status==="done"),de=$.some(j=>j.status==="in_progress"),Et=pe?"done":de?"in_progress":"open",$t=$.filter(j=>j.status==="done").length,Rt=R===T?"Roadmap":`Decision: ${R}`;h.push(`${c[Et]} ${Rt} (${$t}/${$.length} done)`);for(let j of E){if(j.status==="stale"||R===T&&j.status==="done")continue;let vt=u===j.id?" \u2192":"";h.push(` ${c[j.status]||"[?]"}${vt} Phase ${j.phase_number}: ${j.text}`),f(j.id,2)}}let g=R=>i.find(E=>E.id===R),_=g(u),w=_?.decision_name??null,b=_?.phase_number??null,x=_;for(;x&&x.parent_phase_id!=null&&(x=g(x.parent_phase_id),!!x);)w=x.decision_name??w,b=x.phase_number??b;o.close();let k=_?_.phase_number!=null?`${_.decision_name} / Phase ${_.phase_number}: ${_.text}`:`${w} / Phase ${b} \u2192 ${_.text}`:"(unknown)",L=S.join(e,".last-roadmap-cursor"),Ne=null;try{Ne=parseInt(y.readFileSync(L,"utf8").trim(),10)}catch{}let Me=Ne!==u;try{y.writeFileSync(L,String(u),"utf8")}catch{}let Ae=null;if(Me&&w!=null&&b!=null){let R=w===T?S.join(e,"roadmap.md"):S.join(e,"memory",`decision_${r(w)}.md`),E=a(R,b);E&&(Ae=E.split(`
77
- `))}return{active:!0,currentLabel:k,treeLines:h,advanced:Me,memoLines:Ae}}catch{try{o?.close()}catch{}return t}}process.on("uncaughtException",e=>{process.stderr.write(`cairn: ${e.message}
78
- `),process.exit(0)});var N=process.argv[2];if(N==="--version"||N==="-v"){let e=JSON.parse(y.readFileSync(new URL("../package.json",import.meta.url),"utf8"));console.log(e.version),process.exit(0)}else if(N==="minify"){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{let t,n;try{n=JSON.parse(e)?.tool_input||{},t=n.file_path}catch{process.exit(0)}t||process.exit(0),(n.offset!=null||n.limit!=null)&&process.exit(0),t=S.resolve(t);let s=we(t);s||process.exit(0);let o=S.join(s,"views"),r=S.relative(o,t);!r.startsWith("..")&&!S.isAbsolute(r)&&process.exit(0);let a=K(s),u=ae(s,a)>0,i=a[t];i?.state==="edit-ready"&&(u&&D(s,a),process.exit(0)),i?.state==="compressed"&&(i.state="edit-ready",D(s,a),process.exit(0));let c=S.extname(t).toLowerCase(),p=Fe[c];(!p||!is.has(p))&&(u&&D(s,a),process.exit(0));let m;try{m=y.readFileSync(t,"utf8")}catch{u&&D(s,a),process.exit(0)}let d=m.split(`
79
- `).length,h=p==="vue"?Le(m):re(m,p),f=h.split(`
80
- `).length,g=d>0?Math.round((1-f/d)*100):0,_=Ge(s,t);y.mkdirSync(S.dirname(_),{recursive:!0}),y.writeFileSync(_,h,"utf8");let w=i?.readCount??0;a[t]={tempPath:_,state:"compressed",minifiedAt:y.statSync(t).mtimeMs,readCount:w+1},D(s,a);let b=f>ze,x=w>0;if(x||b){let k=Ke(h,p),L=x?`[cairn: ${d} \u2192 ${f} lines | seen \xD7${w+1} this session]`:`[cairn: ${d} \u2192 outline (${f} minified lines)]`;process.stderr.write(`${L}
75
+ `)}`),r.push(" \u2192 Call cairn_resume for full index status and open todos."),r}async function St(e){let t={active:!1},n=x.join(e,"index.db");if(!y.existsSync(n))return t;let s;try{({DatabaseSync:s}=await import("node:sqlite"))}catch{return t}let o;try{o=new s(n,{readonly:!0})}catch{return t}let r=c=>c.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");function a(c,u){if(!y.existsSync(c))return null;let i=y.readFileSync(c,"utf8"),l=!1,d=!1,f=[];for(let p of i.split(/\r?\n/)){if(/^##\s+Phases\s*$/i.test(p)){l=!0;continue}if(l&&/^##\s+/.test(p)&&!/^###/.test(p))break;if(!l)continue;let h=/^###\s+Phase\s+(\d+)\s*:\s*(.+?)\s*$/.exec(p);if(h){if(d)break;parseInt(h[1],10)===u&&(f.push(`### Phase ${h[1]}: ${h[2]}`),d=!0);continue}d&&f.push(p)}return f.join(`
76
+ `).trim()||null}try{let u=o.prepare("SELECT phase_id FROM roadmap_cursor WHERE singleton = 1").get()?.phase_id??null;if(u==null)return o.close(),t;let i=o.prepare("SELECT id, decision_name, phase_number, parent_phase_id, text, status, position FROM roadmap_phases ORDER BY decision_name, phase_number, position, id").all(),l={open:"[ ]",in_progress:"[~]",done:"[x]",blocked:"[!]",stale:"[s]"},d=new Map;for(let R of i){let E=R.parent_phase_id??"root";d.has(E)||d.set(E,[]),d.get(E).push(R)}for(let R of d.values())R.sort((E,$)=>E.decision_name&&$.decision_name&&E.decision_name!==$.decision_name?E.decision_name.localeCompare($.decision_name):E.phase_number!=null&&$.phase_number!=null?E.phase_number-$.phase_number:E.position-$.position||E.id-$.id);let f=d.get("root")||[],p=new Map;for(let R of f)R.decision_name!=null&&(p.has(R.decision_name)||p.set(R.decision_name,[]),p.get(R.decision_name).push(R));let h=[],m=(R,E)=>{for(let $ of d.get(R)||[]){if($.status==="stale")continue;let me=u===$.id?" \u2192":"",he=$.phase_number!=null?`Phase ${$.phase_number}: ${$.text}`:$.text;h.push(`${" ".repeat(E)}${l[$.status]||"[?]"}${me} ${he}`),m($.id,E+1)}};for(let[R,E]of p){let $=E.filter(T=>T.status!=="stale");if($.length===0)continue;let me=$.every(T=>T.status==="done"),he=$.some(T=>T.status==="in_progress"),Et=me?"done":he?"in_progress":"open",$t=$.filter(T=>T.status==="done").length,Rt=R===j?"Roadmap":`Decision: ${R}`;h.push(`${l[Et]} ${Rt} (${$t}/${$.length} done)`);for(let T of E){if(T.status==="stale"||R===j&&T.status==="done")continue;let vt=u===T.id?" \u2192":"";h.push(` ${l[T.status]||"[?]"}${vt} Phase ${T.phase_number}: ${T.text}`),m(T.id,2)}}let _=R=>i.find(E=>E.id===R),g=_(u),S=g?.decision_name??null,b=g?.phase_number??null,w=g;for(;w&&w.parent_phase_id!=null&&(w=_(w.parent_phase_id),!!w);)S=w.decision_name??S,b=w.phase_number??b;o.close();let k=g?g.phase_number!=null?`${g.decision_name} / Phase ${g.phase_number}: ${g.text}`:`${S} / Phase ${b} \u2192 ${g.text}`:"(unknown)",L=x.join(e,".last-roadmap-cursor"),Q=null;try{Q=parseInt(y.readFileSync(L,"utf8").trim(),10)}catch{}let oe=Q!==u;try{y.writeFileSync(L,String(u),"utf8")}catch{}let Ae=null;if(oe&&S!=null&&b!=null){let R=S===j?x.join(e,"roadmap.md"):x.join(e,"memory",`decision_${r(S)}.md`),E=a(R,b);E&&(Ae=E.split(`
77
+ `))}return{active:!0,currentLabel:k,treeLines:h,advanced:oe,memoLines:Ae}}catch{try{o?.close()}catch{}return t}}process.on("uncaughtException",e=>{process.stderr.write(`cairn: ${e.message}
78
+ `),process.exit(0)});var N=process.argv[2];if(N==="--version"||N==="-v"){let e=JSON.parse(y.readFileSync(new URL("../package.json",import.meta.url),"utf8"));console.log(e.version),process.exit(0)}else if(N==="minify"){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{let t,n;try{n=JSON.parse(e)?.tool_input||{},t=n.file_path}catch{process.exit(0)}t||process.exit(0),(n.offset!=null||n.limit!=null)&&process.exit(0),t=x.resolve(t);let s=Ee(t);s||process.exit(0);let o=x.join(s,"views"),r=x.relative(o,t);!r.startsWith("..")&&!x.isAbsolute(r)&&process.exit(0);let a=K(s),u=ue(s,a)>0,i=a[t];i?.state==="edit-ready"&&(u&&D(s,a),process.exit(0)),i?.state==="compressed"&&(i.state="edit-ready",D(s,a),process.exit(0));let l=x.extname(t).toLowerCase(),d=Fe[l];(!d||!is.has(d))&&(u&&D(s,a),process.exit(0));let f;try{f=y.readFileSync(t,"utf8")}catch{u&&D(s,a),process.exit(0)}let p=f.split(`
79
+ `).length,h=d==="vue"?Le(f):ce(f,d),m=h.split(`
80
+ `).length,_=p>0?Math.round((1-m/p)*100):0,g=Ge(s,t);y.mkdirSync(x.dirname(g),{recursive:!0}),y.writeFileSync(g,h,"utf8");let S=i?.readCount??0;a[t]={tempPath:g,state:"compressed",minifiedAt:y.statSync(t).mtimeMs,readCount:S+1},D(s,a);let b=m>ze,w=S>0;if(w||b){let k=Ke(h,d),L=w?`[cairn: ${p} \u2192 ${m} lines | seen \xD7${S+1} this session]`:`[cairn: ${p} \u2192 outline (${m} minified lines)]`;ae(`[cairn] Expected step, not a failure: ${x.basename(t)} was served as an outline (${p} lines \u2192 ${m} minified). The outline is in context; Read("${g}") for the full minified view.`,`${L}
81
81
  ${k}
82
- Full minified view: Read("${_}")
83
- `)}else process.stderr.write(`[cairn: ${d} \u2192 ${f} lines (-${g}%)]
82
+ Full minified view: Read("${g}")`)}else ae(`[cairn] Expected step, not a failure: ${x.basename(t)} was served minified (${p} \u2192 ${m} lines, -${_}%). The content is in context; Read("${g}") for the cached view.`,`[cairn: ${p} \u2192 ${m} lines (-${_}%)]
84
83
  ${h}
85
- Cached view: Read("${_}")
86
- `);process.exit(2)})}else if(N==="edit-guard"){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{let t="(unknown)",n="Edit";try{let p=JSON.parse(e);t=p?.tool_input?.file_path||"(unknown)",n=p?.tool_name||"Edit"}catch{}let s=S.resolve(t),o=we(s);o||process.exit(0);let r=S.join(o,"views"),a=S.relative(r,s);if(!a.startsWith("..")&&!S.isAbsolute(a)){let p=K(o),m=Object.entries(p).find(([,h])=>h.tempPath===s),d=m?`Edit the source file instead: Edit("${m[0]}")`:"Edit the original source file, not the .cairn/views/ cache.";Pe(`[cairn] That path is a cached view, not the source \u2014 it is read-only and is overwritten on the next read. ${d}`)}let l=K(o),u=ae(o,l),i=l[s];i||(u>0&&D(o,l),process.exit(0)),n==="Write"&&(delete l[s],D(o,l),process.exit(0)),i.state==="edit-ready"&&(delete l[s],D(o,l),process.exit(0)),i.state="edit-ready",D(o,l);let c=null;try{let p=y.readFileSync(s,"utf8");p.split(`
87
- `).length<=300&&(c=p)}catch{}c!==null?Pe(`[cairn] Expected step, not a failure: this file was shown compressed, so the edit was built from partial text. The full source has been provided in context \u2014 re-apply the same edit, or Read("${t}") first if you do not see it.`,`[cairn] Full source of ${t} (the compressed view you saw is not editable text \u2014 use the exact content below, then re-apply your Edit; the guard is now cleared):
84
+ Cached view: Read("${g}")`)})}else if(N==="edit-guard"){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{let t="(unknown)",n="Edit";try{let d=JSON.parse(e);t=d?.tool_input?.file_path||"(unknown)",n=d?.tool_name||"Edit"}catch{}let s=x.resolve(t),o=Ee(s);o||process.exit(0);let r=x.join(o,"views"),a=x.relative(r,s);if(!a.startsWith("..")&&!x.isAbsolute(a)){let d=K(o),f=Object.entries(d).find(([,h])=>h.tempPath===s),p=f?`Edit the source file instead: Edit("${f[0]}")`:"Edit the original source file, not the .cairn/views/ cache.";ae(`[cairn] That path is a cached view, not the source \u2014 it is read-only and is overwritten on the next read. ${p}`)}let c=K(o),u=ue(o,c),i=c[s];i||(u>0&&D(o,c),process.exit(0)),n==="Write"&&(delete c[s],D(o,c),process.exit(0)),i.state==="edit-ready"&&(delete c[s],D(o,c),process.exit(0)),i.state="edit-ready",D(o,c);let l=null;try{let d=y.readFileSync(s,"utf8");d.split(`
85
+ `).length<=300&&(l=d)}catch{}l!==null?ae(`[cairn] Expected step, not a failure: this file was shown compressed, so the edit was built from partial text. The full source has been provided in context \u2014 re-apply the same edit, or Read("${t}") first if you do not see it.`,`[cairn] Full source of ${t} (the compressed view you saw is not editable text \u2014 use the exact content below, then re-apply your Edit; the guard is now cleared):
88
86
 
89
- ${c}`):Pe(`[cairn] Expected step, not a failure: this file was shown compressed. Read("${t}") to load the real source (it comes through in full now), then re-apply the same edit.`)})}else if(N==="roadmap-capture"){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",async()=>{let t;try{t=JSON.parse(e)}catch{process.exit(0)}let n=t?.tool_name||"",s=t?.tool_input||{},o=process.cwd(),r=S.join(o,".cairn");y.existsSync(r)||process.exit(0);let a=S.join(r,"index.db");y.existsSync(a)||process.exit(0);let l;try{({DatabaseSync:l}=await import("node:sqlite"))}catch{process.exit(0)}let u=/exit.?plan.?mode/i.test(n),i=/todo.?write/i.test(n);!u&&!i&&process.exit(0);let c=null,p;try{if(u){let d=s.plan;(typeof d!="string"||!d.trim())&&process.exit(0);let h=st(d);if(p=new l(a),te(p),(p.prepare("SELECT phase_id FROM main.roadmap_cursor WHERE singleton = 1").get()?.phase_id??null)==null){let g=gt(p,null);g.id!=null&&yt(p,g.id)}h.added.length>0&&(c=`[cairn] roadmap: captured ${h.added.length} phase(s) from plan${h.skipped.length?` (${h.skipped.length} already present)`:""}.`)}else if(i){p=new l(a);let d=ot(p,s.todos);d.seeded?c=`[cairn] roadmap: seeded ${d.seeded} phase(s) from todos.`:d.inserted>0&&(c=`[cairn] roadmap: linked ${d.inserted} new sub-task(s) to the current phase.`)}}catch(d){process.stderr.write(`[cairn] roadmap-capture skipped: ${d.message}
90
- `);try{p?.close()}catch{}process.exit(0)}let m=p?ue(p):null;try{p?.close()}catch{}m&&(c=c?`${c} ${m}`:m),c&&process.stdout.write(JSON.stringify({systemMessage:c})),process.exit(0)})}else if(N==="validate-map"){let e=S.join(process.cwd(),".cairn");y.existsSync(e)||process.exit(0);let t=K(e),n=ae(e,t);for(let s of Object.values(t))s.readCount=0;D(e,t),n>0&&process.stdout.write(`[cairn] Cleaned minify map: ${n} stale entr${n===1?"y":"ies"} removed
91
- `),process.exit(0)}else if(N==="checkpoint"&&process.argv[3]==="--auto"){let e=`Auto-checkpoint at ${new Date().toISOString()}`,t=[],n=[];try{let s=S.join(process.cwd(),".cairn"),o=S.join(s,"session.json");y.existsSync(o)&&(t=JSON.parse(y.readFileSync(o,"utf8")).notes||[]);let r=K(s);n=Object.entries(r).filter(([,a])=>(a.readCount??0)>0).map(([a])=>a)}catch{}xe(null,{message:e,active_files:n,notes:t,auto:!0}),process.exit(0)}else if(N==="session-tick"){let e=process.cwd(),t=S.join(e,".cairn");y.existsSync(t)||process.exit(0);let n={};if(!process.stdin.isTTY)try{n=JSON.parse(y.readFileSync(0,"utf8"))||{}}catch{}let s=[];try{let i=`Auto-checkpoint at ${new Date().toISOString()}`,c=[],p=S.join(t,"session.json");if(y.existsSync(p))try{c=JSON.parse(y.readFileSync(p,"utf8")).notes||[]}catch{}let m=K(t),d=Object.entries(m).filter(([,h])=>(h.readCount??0)>0).map(([h])=>h);xe(null,{message:i,active_files:d,notes:c,auto:!0}),s.push("\u2713 checkpoint saved")}catch{}try{let i=cs(e);i>0&&s.push(`memory backed up (${i})`)}catch{}let o=[],r=null;try{let i=S.join(t,"index.db");if(y.existsSync(i)){let{DatabaseSync:c}=await import("node:sqlite"),p=new c(i);try{te(p),r=ue(p);try{o=rt(p,e).candidates}catch{}}finally{p.close()}}}catch{}let a="";try{let i=await St(t);if(i.active){s.push(`roadmap ${i.advanced?"updated":"on track"}: ${i.currentLabel}`);let c=["[cairn] Production roadmap (\u2192 = cursor / current phase):",...i.treeLines.map(p=>" "+p)];i.memoLines&&c.push("","\u2500\u2500 Current phase detail (from roadmap.md) \u2500\u2500",...i.memoLines,"\u2500\u2500 (re-read after each phase to confirm direction) \u2500\u2500"),c.push("","Keep this current via cairn_roadmap on MATERIAL change (phase done / blocked / new) \u2014 not every turn."),a=c.join(`
92
- `)}}catch{}if(r&&(s.push("ROADMAP.md not updated \u2014 see warning"),a=a?`${a}
87
+ ${l}`):ae(`[cairn] Expected step, not a failure: this file was shown compressed. Read("${t}") to load the real source (it comes through in full now), then re-apply the same edit.`)})}else if(N==="roadmap-capture"){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",async()=>{let t;try{t=JSON.parse(e)}catch{process.exit(0)}let n=t?.tool_name||"",s=t?.tool_input||{},o=process.cwd(),r=x.join(o,".cairn");y.existsSync(r)||process.exit(0);let a=x.join(r,"index.db");y.existsSync(a)||process.exit(0);let c;try{({DatabaseSync:c}=await import("node:sqlite"))}catch{process.exit(0)}let u=/exit.?plan.?mode/i.test(n),i=/todo.?write/i.test(n);!u&&!i&&process.exit(0);let l=null,d;try{if(u){let p=s.plan;(typeof p!="string"||!p.trim())&&process.exit(0);let h=st(p);if(d=new c(a),ne(d),(d.prepare("SELECT phase_id FROM main.roadmap_cursor WHERE singleton = 1").get()?.phase_id??null)==null){let _=gt(d,null);_.id!=null&&yt(d,_.id)}h.added.length>0&&(l=`[cairn] roadmap: captured ${h.added.length} phase(s) from plan${h.skipped.length?` (${h.skipped.length} already present)`:""}.`)}else if(i){d=new c(a);let p=ot(d,s.todos);p.seeded?l=`[cairn] roadmap: seeded ${p.seeded} phase(s) from todos.`:p.inserted>0&&(l=`[cairn] roadmap: linked ${p.inserted} new sub-task(s) to the current phase.`)}}catch(p){process.stderr.write(`[cairn] roadmap-capture skipped: ${p.message}
88
+ `);try{d?.close()}catch{}process.exit(0)}let f=d?fe(d):null;try{d?.close()}catch{}f&&(l=l?`${l} ${f}`:f),l&&process.stdout.write(JSON.stringify({systemMessage:l})),process.exit(0)})}else if(N==="validate-map"){let e=x.join(process.cwd(),".cairn");y.existsSync(e)||process.exit(0);let t=K(e),n=ue(e,t);for(let s of Object.values(t))s.readCount=0;D(e,t),n>0&&process.stdout.write(`[cairn] Cleaned minify map: ${n} stale entr${n===1?"y":"ies"} removed
89
+ `),process.exit(0)}else if(N==="checkpoint"&&process.argv[3]==="--auto"){let e=`Auto-checkpoint at ${new Date().toISOString()}`,t=[],n=[];try{let s=x.join(process.cwd(),".cairn"),o=x.join(s,"session.json");y.existsSync(o)&&(t=JSON.parse(y.readFileSync(o,"utf8")).notes||[]);let r=K(s);n=Object.entries(r).filter(([,a])=>(a.readCount??0)>0).map(([a])=>a)}catch{}ke(null,{message:e,active_files:n,notes:t,auto:!0}),process.exit(0)}else if(N==="session-tick"){let e=process.cwd(),t=x.join(e,".cairn");if(y.existsSync(t)||process.exit(0),!process.stdin.isTTY)try{y.readFileSync(0,"utf8")}catch{}let n=[];try{let c=`Auto-checkpoint at ${new Date().toISOString()}`,u=[],i=x.join(t,"session.json");if(y.existsSync(i))try{u=JSON.parse(y.readFileSync(i,"utf8")).notes||[]}catch{}let l=K(t),d=Object.entries(l).filter(([,f])=>(f.readCount??0)>0).map(([f])=>f);ke(null,{message:c,active_files:d,notes:u,auto:!0}),n.push("\u2713 checkpoint saved")}catch{}try{let c=cs(e);c>0&&n.push(`memory backed up (${c})`)}catch{}let s=[],o=null;try{let c=x.join(t,"index.db");if(y.existsSync(c)){let{DatabaseSync:u}=await import("node:sqlite"),i=new u(c);try{ne(i),o=fe(i);try{s=rt(i,e).candidates}catch{}}finally{i.close()}}}catch{}let r="";try{let c=await St(t);if(c.active){n.push(`roadmap ${c.advanced?"updated":"on track"}: ${c.currentLabel}`);let u=["[cairn] Production roadmap (\u2192 = cursor / current phase):",...c.treeLines.map(i=>" "+i)];c.memoLines&&u.push("","\u2500\u2500 Current phase detail (from roadmap.md) \u2500\u2500",...c.memoLines,"\u2500\u2500 (re-read after each phase to confirm direction) \u2500\u2500"),u.push("","Keep this current via cairn_roadmap on MATERIAL change (phase done / blocked / new) \u2014 not every turn."),r=u.join(`
90
+ `)}}catch{}if(o&&(n.push("ROADMAP.md not updated \u2014 see warning"),r=r?`${r}
93
91
 
94
- ${r}`:r),o.length>0){s.push(`${o.length} phase(s) may be done \u2014 confirm with user`);let i=["","[cairn] Possible COMPLETED phase(s) detected from recent commits \u2014","CONFIRM WITH THE USER before marking done; do NOT mark done unilaterally:"];for(let c of o)i.push(` \u2022 Phase ${c.phase_number}: ${c.text} (commit ${c.commit}, ${c.confidence}) \u2192 if confirmed: cairn_roadmap set_status ${c.phase_id} done`);a=a?a+`
95
- `+i.join(`
96
- `):i.join(`
97
- `).trimStart()}let l=null;try{let i=JSON.parse(y.readFileSync(S.join(t,"session.json"),"utf8")),c=Je({cwd:e,session:i,transcriptPath:n.transcript_path});if(c&&Be(t,c.signature)){l=c;let p=`
98
- ${c.line}
99
- ${c.guidance}`;a=a?a+`
100
- `+p:p.trimStart()}}catch{}s.length===0&&!l&&process.exit(0);let u={systemMessage:s.length>0?`[cairn] ${s.join(" \xB7 ")}${l?`
101
- ${l.line}`:""}`:l.line};a&&(u.additionalContext=a),process.stdout.write(JSON.stringify(u)),process.exit(0)}else if(N==="repair-memory"){let e=process.argv.includes("--dry-run"),t=process.cwd();y.existsSync(S.join(t,".cairn"))||(console.error("[cairn] Not a cairn project (no .cairn/ here). Run this from the project root."),process.exit(1)),Ce(t);let n=Qe(ye(),{dryRun:e});if(n.reason&&(console.error(`[cairn] ${n.reason}: ${n.dir}`),process.exit(1)),console.log(`Memory index: ${n.dir}`),console.log(` files on disk : ${n.files_on_disk}`),console.log(` already listed: ${n.already_indexed}`),console.log(` missing : ${n.restored}`),n.restored>0){for(let s of n.restored_entries.slice(0,20))console.log(` + ${s.name}${s.type?" ["+s.type+"]":""} (${s.file})`);n.restored_entries.length>20&&console.log(` \u2026 and ${n.restored_entries.length-20} more`)}if(n.dangling.length>0){console.log(` dangling : ${n.dangling.length} pointer(s) whose file is gone (left alone)`);for(let s of n.dangling.slice(0,10))console.log(` ? ${s.name} (${s.file})`)}n.unreadable.length>0&&console.log(` unreadable : ${n.unreadable.length} file(s) skipped`),e?console.log(n.restored>0?`
92
+ ${o}`:o),s.length>0){n.push(`${s.length} phase(s) may be done \u2014 confirm with user`);let c=["","[cairn] Possible COMPLETED phase(s) detected from recent commits \u2014","CONFIRM WITH THE USER before marking done; do NOT mark done unilaterally:"];for(let u of s)c.push(` \u2022 Phase ${u.phase_number}: ${u.text} (commit ${u.commit}, ${u.confidence}) \u2192 if confirmed: cairn_roadmap set_status ${u.phase_id} done`);r=r?r+`
93
+ `+c.join(`
94
+ `):c.join(`
95
+ `).trimStart()}n.length===0&&process.exit(0);let a={systemMessage:`[cairn] ${n.join(" \xB7 ")}`};r&&(a.additionalContext=r),process.stdout.write(JSON.stringify(a)),process.exit(0)}else if(N==="repair-memory"){let e=process.argv.includes("--dry-run"),t=process.cwd();y.existsSync(x.join(t,".cairn"))||(console.error("[cairn] Not a cairn project (no .cairn/ here). Run this from the project root."),process.exit(1)),Ce(t);let n=Qe(Se(),{dryRun:e});if(n.reason&&(console.error(`[cairn] ${n.reason}: ${n.dir}`),process.exit(1)),console.log(`Memory index: ${n.dir}`),console.log(` files on disk : ${n.files_on_disk}`),console.log(` already listed: ${n.already_indexed}`),console.log(` missing : ${n.restored}`),n.restored>0){for(let s of n.restored_entries.slice(0,20))console.log(` + ${s.name}${s.type?" ["+s.type+"]":""} (${s.file})`);n.restored_entries.length>20&&console.log(` \u2026 and ${n.restored_entries.length-20} more`)}if(n.dangling.length>0){console.log(` dangling : ${n.dangling.length} pointer(s) whose file is gone (left alone)`);for(let s of n.dangling.slice(0,10))console.log(` ? ${s.name} (${s.file})`)}n.unreadable.length>0&&console.log(` unreadable : ${n.unreadable.length} file(s) skipped`),e?console.log(n.restored>0?`
102
96
  Dry run \u2014 nothing written. Re-run without --dry-run to restore them.`:`
103
97
  Dry run \u2014 nothing to restore.`):n.repaired?console.log(`
104
98
  Restored ${n.restored} pointer(s). Previous index kept as ${n.backup}.`):console.log(`
105
- Index already lists every memory file. Nothing to do.`),process.exit(0)}else if(N==="memory-restore"){let e=process.cwd();y.existsSync(S.join(e,".cairn"))||process.exit(0);try{let t=ls(e);t>0&&process.stdout.write(`[cairn] Restored ${t} memory file(s) from .cairn/memory backup (Claude store was empty)
106
- `)}catch{}process.exit(0)}else if(N==="resume-hint"){let e=S.join(process.cwd(),".cairn"),t=S.join(e,"session.json"),n=S.join(e,"index.db"),s=S.join(e,".hint-lock"),o=1800*1e3,r=process.cwd()===Z.homedir();if(!r&&y.existsSync(e)&&(y.existsSync(n)||y.existsSync(t))){let f=S.join(e,".cairn-project");if(!y.existsSync(f))try{y.writeFileSync(f,"","utf8"),process.stdout.write(`[cairn] Repaired: wrote .cairn-project sentinel for hook compatibility.
99
+ Index already lists every memory file. Nothing to do.`),process.exit(0)}else if(N==="memory-restore"){let e=process.cwd();y.existsSync(x.join(e,".cairn"))||process.exit(0);try{let t=ls(e);t>0&&process.stdout.write(`[cairn] Restored ${t} memory file(s) from .cairn/memory backup (Claude store was empty)
100
+ `)}catch{}process.exit(0)}else if(N==="resume-hint"){let e=x.join(process.cwd(),".cairn"),t=x.join(e,"session.json"),n=x.join(e,"index.db"),s=x.join(e,".hint-lock"),o=1800*1e3,r=process.cwd()===Z.homedir();if(!r&&y.existsSync(e)&&(y.existsSync(n)||y.existsSync(t))){let g=x.join(e,".cairn-project");if(!y.existsSync(g))try{y.writeFileSync(g,"","utf8"),process.stdout.write(`[cairn] Repaired: wrote .cairn-project sentinel for hook compatibility.
107
101
  `)}catch{}}if(!r&&y.existsSync(e))try{as()&&process.stdout.write(`[cairn] Repaired: declared the roadmap slot (${X}) in ~/.claude.json.
108
- `)}catch{}if(!r&&y.existsSync(n))try{let{DatabaseSync:f}=await import("node:sqlite"),g=new f(n,{readonly:!0}),_=null;try{_=ue(g)}finally{g.close()}_&&process.stdout.write(`${_}
109
- `)}catch{}{let f=[S.join(process.cwd(),".claude","settings.json"),S.join(Z.homedir(),".claude","settings.json")];for(let g of f)try{if(!y.existsSync(g))continue;let _=y.readFileSync(g,"utf8"),w=JSON.parse(_),b=w?.hooks?.PreToolUse;if(!Array.isArray(b))continue;let x=!1;for(let k of b)if(!(k.matcher!=="Edit"||!Array.isArray(k.hooks)))for(let L of k.hooks)L.command==="cairn set-mode edit"&&(L.command="cairn edit-guard",x=!0);x&&(y.writeFileSync(g,JSON.stringify(w,null,2),"utf8"),process.stdout.write(`[cairn] Repaired: migrated cairn set-mode \u2192 cairn edit-guard in ${g}
110
- `))}catch{}}let a="";if(!process.stdin.isTTY)try{a=(JSON.parse(y.readFileSync(0,"utf8"))?.prompt||"").toLowerCase()}catch{}let u=/\b(resume|continue|pick up|where (were|did) (we|i)|last session|carry on|what('s| is) next|what (were|was) (we|i)|start|begin)\b/.test(a);y.existsSync(t)||(y.existsSync(n)||(y.existsSync(s)&&Date.now()-y.statSync(s).mtimeMs<o&&process.exit(0),y.mkdirSync(e,{recursive:!0}),y.writeFileSync(s,new Date().toISOString(),"utf8"),process.stdout.write(`[cairn] No index found. Run cairn_maintain to index this project.
111
- `)),process.exit(0)),y.existsSync(s)&&Date.now()-y.statSync(s).mtimeMs<o&&process.exit(0);let i=JSON.parse(y.readFileSync(t,"utf8")),c=new Date(i.checkpoint_at).toLocaleString(),p=/^Auto-checkpoint\b/.test(i.message||""),m=p&&i.last_manual_message||i.message,d=p&&i.last_manual_checkpoint_at?new Date(i.last_manual_checkpoint_at).toLocaleString():c,h=[`[cairn] Prior session: "${m}" (${d}).`,"[cairn] SESSION: ALWAYS call cairn_resume FIRST when asked to resume, continue, or recall prior work \u2014 do NOT substitute git log or file reads. cairn_resume includes commits_since_checkpoint so you can cross-reference checkpoint notes against what was shipped. At end of session, and before any /clear or /compact, call cairn_checkpoint with message + active_files + notes + would_be_lost (what a fresh session would NOT know).","[cairn] TOOLS: NEVER use Bash to run cat, grep, head, tail, find, or ls for file inspection \u2014 always use the Read, Grep, or Glob tools instead. Prefer cairn_search / cairn_bundle / cairn_describe over manual file browsing. Use cairn_outline for structural overview, cairn_todos for backlog, cairn_security before PRs.","[cairn] MEMORY: IMPORTANT \u2014 call cairn_memo IMMEDIATELY and SILENTLY (do NOT ask the user, do NOT list what you are about to save, do NOT confirm afterward) when you observe \u2014 preference: user corrects/confirms your behaviour; experience: non-trivial problem solved; decision: architectural choice made; knowledge: non-obvious codebase fact discovered. cairn_employ_memory is explicit only \u2014 never call it unless asked."];if(!u){let f=se(process.cwd(),i);f.recorded&&h.push(`[cairn] ${Se(f)}`)}u&&h.push(["[cairn] RESUME \u2014 checkpoint loaded inline:",..._t(process.cwd(),i)].join(`
112
- `)),process.stdout.write(h.join(`
102
+ `)}catch{}if(!r&&y.existsSync(n))try{let{DatabaseSync:g}=await import("node:sqlite"),S=new g(n,{readonly:!0}),b=null;try{b=fe(S)}finally{S.close()}b&&process.stdout.write(`${b}
103
+ `)}catch{}{let g=[x.join(process.cwd(),".claude","settings.json"),x.join(Z.homedir(),".claude","settings.json")];for(let S of g)try{if(!y.existsSync(S))continue;let b=y.readFileSync(S,"utf8"),w=JSON.parse(b),k=w?.hooks?.PreToolUse;if(!Array.isArray(k))continue;let L=!1;for(let Q of k)if(!(Q.matcher!=="Edit"||!Array.isArray(Q.hooks)))for(let oe of Q.hooks)oe.command==="cairn set-mode edit"&&(oe.command="cairn edit-guard",L=!0);L&&(y.writeFileSync(S,JSON.stringify(w,null,2),"utf8"),process.stdout.write(`[cairn] Repaired: migrated cairn set-mode \u2192 cairn edit-guard in ${S}
104
+ `))}catch{}}let a="",c="";if(!process.stdin.isTTY)try{let g=JSON.parse(y.readFileSync(0,"utf8"));a=(g?.prompt||"").toLowerCase(),typeof g?.transcript_path=="string"&&(c=g.transcript_path)}catch{}let i=/\b(resume|continue|pick up|where (were|did) (we|i)|last session|carry on|what('s| is) next|what (were|was) (we|i)|start|begin)\b/.test(a);y.existsSync(t)||(y.existsSync(n)||(y.existsSync(s)&&Date.now()-y.statSync(s).mtimeMs<o&&process.exit(0),y.mkdirSync(e,{recursive:!0}),y.writeFileSync(s,new Date().toISOString(),"utf8"),process.stdout.write(`[cairn] No index found. Run cairn_maintain to index this project.
105
+ `)),process.exit(0));let l=null;try{let g=JSON.parse(y.readFileSync(t,"utf8")),S=Je({cwd:process.cwd(),session:g,transcriptPath:c});S&&Be(e,S.signature)&&(l=`${S.line}
106
+ ${S.guidance}`)}catch{}y.existsSync(s)&&Date.now()-y.statSync(s).mtimeMs<o&&(l&&process.stdout.write(l+`
107
+ `),process.exit(0));let d=JSON.parse(y.readFileSync(t,"utf8")),f=new Date(d.checkpoint_at).toLocaleString(),p=/^Auto-checkpoint\b/.test(d.message||""),h=p&&d.last_manual_message||d.message,m=p&&d.last_manual_checkpoint_at?new Date(d.last_manual_checkpoint_at).toLocaleString():f,_=[`[cairn] Prior session: "${h}" (${m}).`,"[cairn] SESSION: ALWAYS call cairn_resume FIRST when asked to resume, continue, or recall prior work \u2014 do NOT substitute git log or file reads. cairn_resume includes commits_since_checkpoint so you can cross-reference checkpoint notes against what was shipped. At end of session, and before any /clear or /compact, call cairn_checkpoint with message + active_files + notes + would_be_lost (what a fresh session would NOT know).","[cairn] TOOLS: NEVER use Bash to run cat, grep, head, tail, find, or ls for file inspection \u2014 always use the Read, Grep, or Glob tools instead. Prefer cairn_search / cairn_bundle / cairn_describe over manual file browsing. Use cairn_outline for structural overview, cairn_todos for backlog, cairn_security before PRs.","[cairn] MEMORY: IMPORTANT \u2014 call cairn_memo IMMEDIATELY and SILENTLY (do NOT ask the user, do NOT list what you are about to save, do NOT confirm afterward) when you observe \u2014 preference: user corrects/confirms your behaviour; experience: non-trivial problem solved; decision: architectural choice made; knowledge: non-obvious codebase fact discovered. cairn_employ_memory is explicit only \u2014 never call it unless asked.",`[cairn] CONTEXT: you cannot see your own token usage, but cairn can and does \u2014 it measures this session's real usage from the transcript on EVERY prompt and prints a "[cairn] Stopping point:" block here once it passes 90% of the context window, with instructions to offer the user a checkpoint + /clear or /compact. So: if that block is absent you are not near the limit, and if the user asks about context, say cairn is watching it and will say so at 90% \u2014 do NOT reply that cairn has no such feature, and do NOT estimate a percentage yourself. When the block does appear, act on it before anything else.`];if(!i){let g=re(process.cwd(),d);g.recorded&&_.push(`[cairn] ${be(g)}`)}i&&_.push(["[cairn] RESUME \u2014 checkpoint loaded inline:",..._t(process.cwd(),d)].join(`
108
+ `)),l&&_.push(l),process.stdout.write(_.join(`
113
109
  `)+`
114
- `),y.writeFileSync(s,new Date().toISOString(),"utf8"),process.exit(0)}else if(N==="session-start"){let e={};if(!process.stdin.isTTY)try{e=JSON.parse(y.readFileSync(0,"utf8"))||{}}catch{}let t=typeof e.cwd=="string"&&e.cwd?e.cwd:process.cwd(),n=S.join(t,".cairn"),s=S.join(n,"session.json");y.existsSync(s)||process.exit(0);let o=typeof e.source=="string"?e.source:"",r;try{r=JSON.parse(y.readFileSync(s,"utf8"))}catch{process.exit(0)}Ye(n);let a=/^Auto-checkpoint\b/.test(r.message||""),l=a&&r.last_manual_message||r.message||"(no message recorded)",u=o==="compact"?"a /compact":o==="clear"?"a /clear":o==="fork"?"a fork":o==="resume"?"a resume":"a restart",i=[`[cairn] Session restored automatically after ${u} \u2014 the user did not have to ask:`,..._t(t,r),"","This IS the prior session state. Do not re-derive it from git log or file reads, and do not","ask the user what they were doing \u2014 it is above. If their first message continues this work,",'carry on from would_lose without making them say "resume" first.',"","If would_lose says nothing was recorded, treat that as a gap rather than an all-clear: cairn","cannot see what the previous session never wrote down."].join(`
115
- `),c=(w,b)=>{let x=String(w).replace(/\s+/g," ").trim();return x.length<=b?x:x.slice(0,b-1)+"\u2026"},p=se(t,r),m=a&&r.last_manual_checkpoint_at||r.checkpoint_at,d=m?new Date(m).toLocaleString():"time unknown",h=[`[cairn] Checkpoint restored after ${u} \u2014 saved ${d}`];h.push(` Working on: ${c(l,140)}`),h.push(p.recorded?` Would be lost: ${c(p.text,200)}`+(p.stale?` (written before the ${p.commits} commit(s) since \u2014 may be stale)`:""):" Would be lost: NOT RECORDED \u2014 nothing says what the last session would lose.");let f=[];r.active_files?.length&&f.push(`${r.active_files.length} active file(s)`),r.notes?.length&&f.push(`${r.notes.length} note(s)`),f.push("full detail"),h.push(` Type "resume" for: ${f.join(", ")}.`);let g=h.join(`
116
- `),_=["[cairn] Session restored from checkpoint.","Lead your next reply with ONE short sentence naming what the previous session left","unfinished. If the user has already asked for something, answer it as normal immediately","after \u2014 this must never delay, replace or override their request. If they have not asked","for anything yet, end that sentence by asking whether to continue the unfinished work.","The details are already in the context you were given; do not re-derive them."].join(" ");process.stdout.write(JSON.stringify({systemMessage:g,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:i,initialUserMessage:_}})),process.exit(0)}else if(N==="roadmap-hint"){let e=S.join(process.cwd(),".cairn"),t=await St(e);t.active||process.exit(0);let n=["[cairn] ROADMAP \u2014 cursor is active.",...t.treeLines.map(s=>"[cairn] "+s),`[cairn] Current: ${t.currentLabel}`];if(t.memoLines){n.push("[cairn] \u2500\u2500\u2500\u2500\u2500 Decision memo (current phase) \u2500\u2500\u2500\u2500\u2500");for(let s of t.memoLines)n.push("[cairn] "+s);n.push("[cairn] \u2500\u2500\u2500\u2500\u2500 (re-read after each phase to confirm direction) \u2500\u2500\u2500\u2500\u2500")}n.push("[cairn] Use cairn_roadmap set_status <id> done (auto-advances), focus <id>, or next to move cursor."),process.stdout.write(n.join(`
110
+ `),y.writeFileSync(s,new Date().toISOString(),"utf8"),process.exit(0)}else if(N==="session-start"){let e={};if(!process.stdin.isTTY)try{e=JSON.parse(y.readFileSync(0,"utf8"))||{}}catch{}let t=typeof e.cwd=="string"&&e.cwd?e.cwd:process.cwd(),n=x.join(t,".cairn"),s=x.join(n,"session.json");y.existsSync(s)||process.exit(0);let o=typeof e.source=="string"?e.source:"",r;try{r=JSON.parse(y.readFileSync(s,"utf8"))}catch{process.exit(0)}Ye(n);let a=/^Auto-checkpoint\b/.test(r.message||""),c=a&&r.last_manual_message||r.message||"(no message recorded)",u=o==="compact"?"a /compact":o==="clear"?"a /clear":o==="fork"?"a fork":o==="resume"?"a resume":"a restart",i=[`[cairn] Session restored automatically after ${u} \u2014 the user did not have to ask:`,..._t(t,r),"","This IS the prior session state. Do not re-derive it from git log or file reads, do not ask","the user what they were doing, and do not ask whether to continue \u2014 it is above, and the",'client that opened this session already said "resume" on their behalf. If their first',"message continues this work, carry on from would_lose without making them ask twice.","","If would_lose says nothing was recorded, treat that as a gap rather than an all-clear: cairn","cannot see what the previous session never wrote down."].join(`
111
+ `),l=(S,b)=>{let w=String(S).replace(/\s+/g," ").trim();return w.length<=b?w:w.slice(0,b-1)+"\u2026"},d=re(t,r),f=a&&r.last_manual_checkpoint_at||r.checkpoint_at,p=f?new Date(f).toLocaleString():"time unknown",h=[`[cairn] Checkpoint restored after ${u} \u2014 saved ${p}`];h.push(` Working on: ${l(c,140)}`),h.push(d.recorded?` Would be lost: ${l(d.text,200)}`+(d.stale?` (written before the ${d.commits} commit(s) since \u2014 may be stale)`:""):" Would be lost: NOT RECORDED \u2014 nothing says what the last session would lose.");let m=[];r.active_files?.length&&m.push(`${r.active_files.length} active file(s)`),r.notes?.length&&m.push(`${r.notes.length} note(s)`),m.push("full detail"),h.push(` Type "resume" for: ${m.join(", ")}.`);let _=h.join(`
112
+ `),g=["[cairn] Session restored from checkpoint.","Lead your next reply with ONE short sentence naming what the previous session left","unfinished, then carry straight on with it. Do NOT ask whether to continue, do NOT ask","what they were working on, and do NOT offer a menu \u2014 the answer is in the context you","were given, so use it rather than re-deriving it. If the user has asked for something,","answer that instead, immediately after the sentence: this must never delay, replace or","override their request."].join(" ");process.stdout.write(JSON.stringify({systemMessage:_,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:i,initialUserMessage:g}})),process.exit(0)}else if(N==="roadmap-hint"){let e=x.join(process.cwd(),".cairn"),t=await St(e);t.active||process.exit(0);let n=["[cairn] ROADMAP \u2014 cursor is active.",...t.treeLines.map(s=>"[cairn] "+s),`[cairn] Current: ${t.currentLabel}`];if(t.memoLines){n.push("[cairn] \u2500\u2500\u2500\u2500\u2500 Decision memo (current phase) \u2500\u2500\u2500\u2500\u2500");for(let s of t.memoLines)n.push("[cairn] "+s);n.push("[cairn] \u2500\u2500\u2500\u2500\u2500 (re-read after each phase to confirm direction) \u2500\u2500\u2500\u2500\u2500")}n.push("[cairn] Use cairn_roadmap set_status <id> done (auto-advances), focus <id>, or next to move cursor."),process.stdout.write(n.join(`
117
113
  `)+`
118
- `),process.exit(0)}else if(N==="install"){let e=process.platform,t=S.join(Z.homedir(),".claude.json"),n={};if(y.existsSync(t))try{n=JSON.parse(y.readFileSync(t,"utf8"))}catch{}n.mcpServers=n.mcpServers||{};let s=!!n.mcpServers.cairn;n.mcpServers.cairn={...s&&typeof n.mcpServers.cairn=="object"?n.mcpServers.cairn:{},command:"cairn-mcp",terminalConnect:wt},y.writeFileSync(t,JSON.stringify(n,null,2),"utf8");let o=S.join(Z.homedir(),".claude");xt(o,!0),console.log("Cairn installed successfully!"),console.log(""),console.log(` Platform : ${e}`),console.log(` MCP : cairn-mcp registered in ${t}${s?" (updated)":""}`),console.log(` Hooks : installed in ${S.join(o,"settings.json")}`),console.log(""),console.log("Active hooks:"),console.log(" PreToolUse[Read] -> cairn minify (compress source files for reading)"),console.log(" PreToolUse[Edit] -> cairn edit-guard (block Edit until re-read with full content)"),console.log(" PreToolUse[Write] -> cairn edit-guard (clear minify state before full file overwrite)"),console.log(" PostToolUse[ExitPlanMode] -> cairn roadmap-capture (approved plan -> roadmap phases)"),console.log(" PostToolUse[TodoWrite] -> cairn roadmap-capture (todos -> roadmap sub-tasks)"),console.log(" Stop -> cairn session-tick (checkpoint + memory backup + roadmap, surfaced)"),console.log(" UserPromptSubmit -> cairn resume-hint (remind Claude of prior session)"),console.log(" UserPromptSubmit -> cairn memory-restore (restore .cairn/memory -> Claude store if empty)"),console.log(" SessionStart -> cairn session-start (re-inject checkpoint on restart / clear / compact / fork)"),console.log(""),console.log("Restart Claude Code to activate the MCP server, then open any project and start working."),console.log("Upgrade any time with: npm install -g @misterhuydo/cairn-mcp"),process.exit(0)}else if(N==="install-hooks"){let e=process.argv.includes("--global"),t=e?S.join(Z.homedir(),".claude"):S.join(process.cwd(),".claude");xt(t,e),console.log(`Cairn hooks installed in ${e?"global (~/.claude/settings.json)":"project (.claude/settings.json)"}`),console.log(""),console.log("Active hooks:"),console.log(" PreToolUse[Read] -> cairn minify (compress source files for reading)"),console.log(" PreToolUse[Edit] -> cairn edit-guard (block Edit until re-read with full content)"),console.log(" PreToolUse[Write] -> cairn edit-guard (clear minify state before full file overwrite)"),console.log(" PostToolUse[ExitPlanMode] -> cairn roadmap-capture (approved plan -> roadmap phases)"),console.log(" PostToolUse[TodoWrite] -> cairn roadmap-capture (todos -> roadmap sub-tasks)"),console.log(" Stop -> cairn session-tick (checkpoint + memory backup + roadmap, surfaced)"),console.log(" UserPromptSubmit -> cairn resume-hint (remind Claude of prior session)"),console.log(" UserPromptSubmit -> cairn memory-restore (restore .cairn/memory -> Claude store if empty)"),console.log(" SessionStart -> cairn session-start (re-inject checkpoint on restart / clear / compact / fork)"),process.exit(0)}else console.error("Usage: cairn <--version | install | install-hooks [--global] | minify | edit-guard | validate-map | checkpoint --auto | session-tick | session-start | resume-hint | roadmap-hint | roadmap-capture | memory-restore | repair-memory [--dry-run]>"),process.exit(1);function xt(e,t){let n=S.join(e,"settings.json"),s={};if(y.existsSync(n))try{s=JSON.parse(y.readFileSync(n,"utf8"))}catch{}s.hooks=s.hooks||{};let o=s.hooks.PreToolUse||[];o.some(d=>d.matcher==="Read"&&d.hooks?.some(h=>h.command==="cairn minify"))||o.push({matcher:"Read",hooks:[{type:"command",command:"cairn minify"}]});let r=o.filter(d=>!(d.matcher==="Edit"&&d.hooks?.some(h=>h.command==="cairn set-mode edit")));r.some(d=>d.matcher==="Edit"&&d.hooks?.some(h=>h.command==="cairn edit-guard"))||r.push({matcher:"Edit",hooks:[{type:"command",command:"cairn edit-guard"}]}),r.some(d=>d.matcher==="Write"&&d.hooks?.some(h=>h.command==="cairn edit-guard"))||r.push({matcher:"Write",hooks:[{type:"command",command:"cairn edit-guard"}]}),s.hooks.PreToolUse=r;let a=(d,h)=>(d||[]).map(f=>({...f,hooks:(f.hooks||[]).filter(g=>!h(g.command))})).filter(f=>(f.hooks||[]).length>0),l=d=>typeof d=="string"&&/sync-memory-(forward|restore)\.(mjs|py)/.test(d),u=a(s.hooks.Stop,d=>d==="cairn checkpoint --auto"||d==="cairn roadmap-hint");u.some(d=>d.hooks?.some(h=>h.command==="cairn session-tick"))||u.push({hooks:[{type:"command",command:"cairn session-tick"}]}),s.hooks.Stop=u;let i=a(s.hooks.UserPromptSubmit,l);i.some(d=>d.hooks?.some(h=>h.command==="cairn resume-hint"))||i.push({hooks:[{type:"command",command:"cairn resume-hint"}]}),i.some(d=>d.hooks?.some(h=>h.command==="cairn memory-restore"))||i.push({hooks:[{type:"command",command:"cairn memory-restore"}]}),s.hooks.UserPromptSubmit=i;let c=a(s.hooks.SessionStart,d=>d==="cairn session-start");c.push({hooks:[{type:"command",command:"cairn session-start"}]}),s.hooks.SessionStart=c;let p=a(s.hooks.PostToolUse,l),m=d=>{p.some(h=>h.matcher===d&&h.hooks?.some(f=>f.command==="cairn roadmap-capture"))||p.push({matcher:d,hooks:[{type:"command",command:"cairn roadmap-capture"}]})};if(m("ExitPlanMode"),m("TodoWrite"),s.hooks.PostToolUse=p,t){let d=S.join(e,"scripts");for(let h of["sync-memory-forward.mjs","sync-memory-restore.mjs","sync-memory-forward.py","sync-memory-restore.py"]){let f=S.join(d,h);if(y.existsSync(f))try{y.unlinkSync(f)}catch{}}}if(!t){let d=S.join(process.cwd(),".cairn");y.mkdirSync(d,{recursive:!0});let h=S.join(d,".cairn-project");y.existsSync(h)||y.writeFileSync(h,"","utf8")}y.mkdirSync(e,{recursive:!0}),y.writeFileSync(n,JSON.stringify(s,null,2),"utf8")}
114
+ `),process.exit(0)}else if(N==="install"){let e=process.platform,t=x.join(Z.homedir(),".claude.json"),n={};if(y.existsSync(t))try{n=JSON.parse(y.readFileSync(t,"utf8"))}catch{}n.mcpServers=n.mcpServers||{};let s=!!n.mcpServers.cairn;n.mcpServers.cairn={...s&&typeof n.mcpServers.cairn=="object"?n.mcpServers.cairn:{},command:"cairn-mcp",terminalConnect:wt},y.writeFileSync(t,JSON.stringify(n,null,2),"utf8");let o=x.join(Z.homedir(),".claude");xt(o,!0),console.log("Cairn installed successfully!"),console.log(""),console.log(` Platform : ${e}`),console.log(` MCP : cairn-mcp registered in ${t}${s?" (updated)":""}`),console.log(` Hooks : installed in ${x.join(o,"settings.json")}`),console.log(""),console.log("Active hooks:"),console.log(" PreToolUse[Read] -> cairn minify (compress source files for reading)"),console.log(" PreToolUse[Edit] -> cairn edit-guard (block Edit until re-read with full content)"),console.log(" PreToolUse[Write] -> cairn edit-guard (clear minify state before full file overwrite)"),console.log(" PostToolUse[ExitPlanMode] -> cairn roadmap-capture (approved plan -> roadmap phases)"),console.log(" PostToolUse[TodoWrite] -> cairn roadmap-capture (todos -> roadmap sub-tasks)"),console.log(" Stop -> cairn session-tick (checkpoint + memory backup + roadmap, surfaced)"),console.log(" UserPromptSubmit -> cairn resume-hint (remind Claude of prior session)"),console.log(" UserPromptSubmit -> cairn memory-restore (restore .cairn/memory -> Claude store if empty)"),console.log(" SessionStart -> cairn session-start (re-inject checkpoint on restart / clear / compact / fork)"),console.log(""),console.log("Restart Claude Code to activate the MCP server, then open any project and start working."),console.log("Upgrade any time with: npm install -g @misterhuydo/cairn-mcp"),process.exit(0)}else if(N==="install-hooks"){let e=process.argv.includes("--global"),t=e?x.join(Z.homedir(),".claude"):x.join(process.cwd(),".claude");xt(t,e),console.log(`Cairn hooks installed in ${e?"global (~/.claude/settings.json)":"project (.claude/settings.json)"}`),console.log(""),console.log("Active hooks:"),console.log(" PreToolUse[Read] -> cairn minify (compress source files for reading)"),console.log(" PreToolUse[Edit] -> cairn edit-guard (block Edit until re-read with full content)"),console.log(" PreToolUse[Write] -> cairn edit-guard (clear minify state before full file overwrite)"),console.log(" PostToolUse[ExitPlanMode] -> cairn roadmap-capture (approved plan -> roadmap phases)"),console.log(" PostToolUse[TodoWrite] -> cairn roadmap-capture (todos -> roadmap sub-tasks)"),console.log(" Stop -> cairn session-tick (checkpoint + memory backup + roadmap, surfaced)"),console.log(" UserPromptSubmit -> cairn resume-hint (remind Claude of prior session)"),console.log(" UserPromptSubmit -> cairn memory-restore (restore .cairn/memory -> Claude store if empty)"),console.log(" SessionStart -> cairn session-start (re-inject checkpoint on restart / clear / compact / fork)"),process.exit(0)}else console.error("Usage: cairn <--version | install | install-hooks [--global] | minify | edit-guard | validate-map | checkpoint --auto | session-tick | session-start | resume-hint | roadmap-hint | roadmap-capture | memory-restore | repair-memory [--dry-run]>"),process.exit(1);function xt(e,t){let n=x.join(e,"settings.json"),s={};if(y.existsSync(n))try{s=JSON.parse(y.readFileSync(n,"utf8"))}catch{}s.hooks=s.hooks||{};let o=s.hooks.PreToolUse||[];o.some(p=>p.matcher==="Read"&&p.hooks?.some(h=>h.command==="cairn minify"))||o.push({matcher:"Read",hooks:[{type:"command",command:"cairn minify"}]});let r=o.filter(p=>!(p.matcher==="Edit"&&p.hooks?.some(h=>h.command==="cairn set-mode edit")));r.some(p=>p.matcher==="Edit"&&p.hooks?.some(h=>h.command==="cairn edit-guard"))||r.push({matcher:"Edit",hooks:[{type:"command",command:"cairn edit-guard"}]}),r.some(p=>p.matcher==="Write"&&p.hooks?.some(h=>h.command==="cairn edit-guard"))||r.push({matcher:"Write",hooks:[{type:"command",command:"cairn edit-guard"}]}),s.hooks.PreToolUse=r;let a=(p,h)=>(p||[]).map(m=>({...m,hooks:(m.hooks||[]).filter(_=>!h(_.command))})).filter(m=>(m.hooks||[]).length>0),c=p=>typeof p=="string"&&/sync-memory-(forward|restore)\.(mjs|py)/.test(p),u=a(s.hooks.Stop,p=>p==="cairn checkpoint --auto"||p==="cairn roadmap-hint");u.some(p=>p.hooks?.some(h=>h.command==="cairn session-tick"))||u.push({hooks:[{type:"command",command:"cairn session-tick"}]}),s.hooks.Stop=u;let i=a(s.hooks.UserPromptSubmit,c);i.some(p=>p.hooks?.some(h=>h.command==="cairn resume-hint"))||i.push({hooks:[{type:"command",command:"cairn resume-hint"}]}),i.some(p=>p.hooks?.some(h=>h.command==="cairn memory-restore"))||i.push({hooks:[{type:"command",command:"cairn memory-restore"}]}),s.hooks.UserPromptSubmit=i;let l=a(s.hooks.SessionStart,p=>p==="cairn session-start");l.push({hooks:[{type:"command",command:"cairn session-start"}]}),s.hooks.SessionStart=l;let d=a(s.hooks.PostToolUse,c),f=p=>{d.some(h=>h.matcher===p&&h.hooks?.some(m=>m.command==="cairn roadmap-capture"))||d.push({matcher:p,hooks:[{type:"command",command:"cairn roadmap-capture"}]})};if(f("ExitPlanMode"),f("TodoWrite"),s.hooks.PostToolUse=d,t){let p=x.join(e,"scripts");for(let h of["sync-memory-forward.mjs","sync-memory-restore.mjs","sync-memory-forward.py","sync-memory-restore.py"]){let m=x.join(p,h);if(y.existsSync(m))try{y.unlinkSync(m)}catch{}}}if(!t){let p=x.join(process.cwd(),".cairn");y.mkdirSync(p,{recursive:!0});let h=x.join(p,".cairn-project");y.existsSync(h)||y.writeFileSync(h,"","utf8")}y.mkdirSync(e,{recursive:!0}),y.writeFileSync(n,JSON.stringify(s,null,2),"utf8")}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@misterhuydo/cairn-mcp",
3
- "version": "1.28.2",
3
+ "version": "1.30.0",
4
4
  "description": "MCP server that gives Claude Code persistent memory across sessions. Index your codebase once, search symbols, bundle source, scan for vulnerabilities, and checkpoint/resume work — across Java, TypeScript, Vue, Python, SQL and more.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",