@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.
- package/dist/cairn-cli.js +64 -68
- 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
|
|
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
|
|
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=[],
|
|
7
|
-
`).filter(
|
|
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],
|
|
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
|
|
11
|
-
`,"utf8")}function
|
|
12
|
-
`).length:0}catch{return null}}function
|
|
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
|
|
14
|
-
`),
|
|
15
|
-
`)[0].slice(0,120),ref:
|
|
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
|
|
19
|
-
`),s=[],o=0;for(let r=0;r<n.length;r++){let a=n[r].trim();if(!a)continue;let{opens:
|
|
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
|
|
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
|
|
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,
|
|
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(
|
|
29
|
-
`):["# Memory Index",""],a=[];for(let
|
|
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
|
|
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
|
|
46
|
-
`),"utf8")}function
|
|
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
|
|
50
|
-
`).trim()||null})).filter(
|
|
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=
|
|
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
|
-
`),
|
|
59
|
+
`),c=n.slice(r).join(`
|
|
60
60
|
`).replace(/^\n+/,""),u=`
|
|
61
61
|
|
|
62
|
-
${o}${
|
|
63
|
-
`+
|
|
64
|
-
`).filter(Boolean)}catch{
|
|
65
|
-
`);return(t===-1?e:e.slice(0,t)).trim()}function
|
|
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
|
|
67
|
-
`)){let
|
|
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=
|
|
70
|
-
`);let n=null;try{n=
|
|
71
|
-
`).join("; "):"(none)"}`)}catch{}let
|
|
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=
|
|
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(),
|
|
77
|
-
`))}return{active:!0,currentLabel:k,treeLines:h,advanced:
|
|
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=
|
|
79
|
-
`).length,h=
|
|
80
|
-
`).length,
|
|
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
|
-
`)
|
|
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
|
-
${
|
|
90
|
-
`);try{
|
|
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=
|
|
92
|
-
`)}}catch{}if(
|
|
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
|
-
${
|
|
95
|
-
`+
|
|
96
|
-
`):
|
|
97
|
-
`).trimStart()}let
|
|
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(
|
|
106
|
-
`)}catch{}process.exit(0)}else if(N==="resume-hint"){let e=
|
|
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:
|
|
109
|
-
`)}catch{}{let
|
|
110
|
-
`))}catch{}}let a="";if(!process.stdin.isTTY)try{
|
|
111
|
-
`)),process.exit(0))
|
|
112
|
-
`))
|
|
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=
|
|
115
|
-
`),
|
|
116
|
-
`),
|
|
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=
|
|
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.
|
|
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",
|