@misterhuydo/cairn-mcp 1.16.0 → 1.17.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/README.md +11 -1
- package/dist/cairn-cli.js +63 -58
- package/dist/index.js +62 -60
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -176,7 +176,17 @@ the first prompt of a session) as well as on every `cairn_roadmap` call, so a wo
|
|
|
176
176
|
that has a roadmap but hasn't touched the roadmap tool this session still shows a
|
|
177
177
|
populated file. It is deterministic (no timestamps, stable ordering, so an unchanged
|
|
178
178
|
plan re-writes byte-identically and leaves clean git diffs), never written as an empty
|
|
179
|
-
placeholder, and
|
|
179
|
+
placeholder, and written atomically (temp file + rename) so a reader never catches a
|
|
180
|
+
half-written plan.
|
|
181
|
+
|
|
182
|
+
An existing `ROADMAP.md` is never destroyed. If the file is there but carries no
|
|
183
|
+
provider marker (hand-written, or from a tool that doesn't stamp its output), cairn
|
|
184
|
+
**adopts** it: the original is renamed to `ROADMAP.bak.md` (or `ROADMAP.bak.2.md`, `.3`,
|
|
185
|
+
… — an existing backup is never overwritten), the generated file records where it came
|
|
186
|
+
from (`migrated-from=ROADMAP.bak.md`), and the result reports `backed_up_to`. If the
|
|
187
|
+
file is stamped by a *different* provider, that's a conflict over who owns the path:
|
|
188
|
+
cairn leaves it completely alone. Any publish that declines returns a `warning` that the
|
|
189
|
+
caller surfaces to you, so a stale plan can't rot in place unnoticed.
|
|
180
190
|
|
|
181
191
|
Editing `roadmap.md` *is* editing the plan — read actions re-seed from it, and the
|
|
182
192
|
end-of-turn hook folds in any hand-edits. Marking a phase **done** prunes it from
|
package/dist/cairn-cli.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import h from"fs";import
|
|
2
|
+
import h from"fs";import q from"os";import g from"path";import{execSync as ye}from"child_process";import Jt from"fast-glob";var Se={".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 Q(e,t,s={}){let{noComments:n=!0,noEmptyLines:o=!0,aggressive:a=!1}=s,c=e;return n&&(c=Ve(c,t)),o&&(c=qe(c)),c=ze(c),a&&(c=Ke(c)),c.trim()}function Ve(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,(s,n)=>n||!s.startsWith("//")?s:"");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 qe(e){return e.split(`
|
|
3
3
|
`).filter(t=>t.trim().length>0).join(`
|
|
4
|
-
`)}function
|
|
4
|
+
`)}function ze(e){return e.split(`
|
|
5
5
|
`).map(t=>t.trimEnd()).join(`
|
|
6
|
-
`)}function
|
|
7
|
-
`).filter(
|
|
8
|
-
`)),
|
|
6
|
+
`)}function Ke(e){return e.replace(/\s+/g," ").replace(/\s*([=+\-*/%<>!&|^~?:;,{}()[\]])\s*/g,"$1").replace(/;\s*}/g,"}").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim()}function xe(e,t={}){let{noStyle:s=!1,noComments:n=!0,noEmptyLines:o=!0,aggressive:a=!1}=t,c=[],p=e.match(/<template>([\s\S]*?)<\/template>/i);if(p){let i=p[1];n&&(i=i.replace(/<!--[\s\S]*?-->/g,"")),o&&(i=i.split(`
|
|
7
|
+
`).filter(u=>u.trim()).join(`
|
|
8
|
+
`)),i=i.replace(/\s+/g," ").trim(),i&&c.push(`<template>${i}</template>`)}let d=e.match(/<script([^>]*)>([\s\S]*?)<\/script>/i);if(d){let i=d[1],u=Q(d[2],"javascript",{noComments:n,noEmptyLines:o,aggressive:a}),m=/setup/i.test(i)?"<script setup>":"<script>";u&&c.push(`${m}${u}</script>`)}if(!s){let i=e.match(/<style([^>]*)>([\s\S]*?)<\/style>/i);if(i){let u=i[2].replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();u&&c.push(`<style${i[1]}>${u}</style>`)}}return c.join(`
|
|
9
9
|
|
|
10
|
-
`)}import
|
|
11
|
-
`)[0].slice(0,120),ref:
|
|
10
|
+
`)}import N from"fs";import B from"path";import Z from"fs";import Xe from"os";import z from"path";var Qe=null;function ee(){return Qe||process.cwd()}function J(){let e=z.join(ee(),".cairn");Z.mkdirSync(z.join(e,"bundles"),{recursive:!0});let t=z.join(e,".cairn-project");return Z.existsSync(t)||Z.writeFileSync(t,"","utf8"),e}function ie(e){return e.replace(/[:/\\]/g,"-").replace(/^-+/,"")}function we(){let e=z.join(Xe.homedir(),".claude","projects",ie(ee()));return Z.existsSync(e)?z.join(e,"memory"):null}var Ze=1e3,et=100*1024;function tt(e,t,s,n){if(e&&typeof e=="object"&&e.ref)return e;let o=typeof e=="string"?e:String(e),a=/^\[\d{4}-\d{2}-\d{2}\]/.test(o)?o:`[${s}] ${o}`;if(a.length<=Ze)return a;let c=B.join(t,"notes");N.mkdirSync(c,{recursive:!0});let d=`note-${new Date().toISOString().replace(/[:.]/g,"-")}-${n}.md`,i=B.join(c,d);return N.writeFileSync(i,a,"utf8"),{description:a.split(`
|
|
11
|
+
`)[0].slice(0,120),ref:B.join(".cairn","notes",d)}}function ae(e,{message:t,active_files:s=[],notes:n=[]}){if(typeof n=="string")try{n=JSON.parse(n)}catch{n=n?[n]:[]}Array.isArray(n)||(n=[]);let o=J(),a=B.join(o,"session.json"),c=new Date().toISOString().slice(0,10),p={};try{let u=e.prepare("SELECT path FROM main.files").all();for(let{path:m}of u)try{p[m]=N.statSync(m).mtimeMs}catch{}}catch{}for(let u of s)try{p[u]=N.statSync(u).mtimeMs}catch{}let d=n.map((u,m)=>tt(u,o,c,m));if(N.existsSync(a))try{if(N.statSync(a).size>et){let m=1;for(;N.existsSync(B.join(o,`session.${m}.json`));)m++;N.renameSync(a,B.join(o,`session.${m}.json`))}}catch{}let i={message:t,checkpoint_at:new Date().toISOString(),active_files:s,notes:d,mtime_snapshot:p};return N.writeFileSync(a,JSON.stringify(i,null,2),"utf8"),{content:[{type:"text",text:JSON.stringify({saved:!0,checkpoint_at:i.checkpoint_at,active_files_tracked:s.length,notes_saved:d.length},null,2)}]}}import D from"fs";import j from"path";import nt from"crypto";var Ee=80;function ce(e){let t=j.dirname(j.resolve(e)),s=j.parse(t).root;for(;;){let n=j.join(t,".cairn");try{if(D.statSync(n).isDirectory()&&D.existsSync(j.join(n,".cairn-project"))&&n.split(j.sep).filter(a=>a===".cairn").length===1)return n}catch{}if(t===s)return null;t=j.dirname(t)}}function be(e,t){let s=nt.createHash("sha256").update(j.resolve(t)).digest("hex").slice(0,6);return j.join(e,"views",`${s}_${j.basename(t)}`)}function U(e){try{return JSON.parse(D.readFileSync(j.join(e,"minify-map.json"),"utf8"))}catch{return{}}}function M(e,t){D.mkdirSync(e,{recursive:!0}),D.writeFileSync(j.join(e,"minify-map.json"),JSON.stringify(t,null,2),"utf8")}function te(e,t){let s=0;for(let[n,o]of Object.entries(t)){let a=!1;if(!D.existsSync(n))a=!0;else if(!D.existsSync(o.tempPath))a=!0;else try{D.statSync(n).mtimeMs>o.minifiedAt&&(a=!0)}catch{a=!0}if(a){if(o.tempPath)try{D.unlinkSync(o.tempPath)}catch{}delete t[n],s++}}return s}function $e(e,t){switch(t){case"javascript":case"typescript":return le(e);case"java":return le(e,{annotations:!0});case"python":return it(e);case"vue":return at(e);case"sql":return ct(e);default:return e.split(`
|
|
12
12
|
`).slice(0,30).join(`
|
|
13
13
|
`)+`
|
|
14
|
-
...`}}function
|
|
15
|
-
`),n=[],o=0;for(let a=0;a<s.length;a++){let
|
|
16
|
-
`)}function
|
|
14
|
+
...`}}function le(e,{annotations:t=!1}={}){let s=e.split(`
|
|
15
|
+
`),n=[],o=0;for(let a=0;a<s.length;a++){let c=s[a].trim();if(!c)continue;let{opens:p,closes:d}=rt(c),i=p-d;if(o===0){let u=st(c);u!==null?n.push(`${a+1}: ${u}`):c==="}"&&n.push("}")}else if(o===1){let u=ot(c,t);u!==null&&n.push(` ${a+1}: ${u}`)}o=Math.max(0,o+i)}return n.join(`
|
|
16
|
+
`)}function st(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)?L(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)?L(e):e==="}"?"}":null}function ot(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")?L(e):null}function L(e){let t=0,s=!1,n="";for(let o=0;o<e.length;o++){let a=e[o];if(s)a===n&&e[o-1]!=="\\"&&(s=!1);else if(a==='"'||a==="'"||a==="`")s=!0,n=a;else if(a==="{"){if(t===0)return e.slice(0,o).trimEnd();t++}else a==="}"&&t--}return e}function rt(e){let t=0,s=0,n=!1,o="";for(let a=0;a<e.length;a++){let c=e[a];n?c===o&&e[a-1]!=="\\"&&(n=!1):c==='"'||c==="'"||c==="`"?(n=!0,o=c):c==="{"?t++:c==="}"&&s++}return{opens:t,closes:s}}function it(e){let t=[],s=e.split(`
|
|
17
17
|
`);for(let n=0;n<s.length;n++){let o=s[n];if(!o.trim())continue;let a=o.trimStart();a.startsWith("import ")||a.startsWith("from ")?t.push(o):(a.startsWith("class ")||a.startsWith("def ")||a.startsWith("async def "))&&t.push(`${n+1}: ${o.trim().replace(/:(\s*)$/,":")}`)}return t.join(`
|
|
18
|
-
`)}function
|
|
19
|
-
`)}function
|
|
18
|
+
`)}function at(e){let t=[];for(let n of e.matchAll(/<(template|script|style)(\s[^>]*)?\s*>/g))t.push(n[0]);let s=e.match(/<script(?:\s[^>]*)?\s*>([\s\S]*?)<\/script>/);if(s){let n=le(s[1]);n.trim()&&(t.push("// script:"),t.push(n))}return t.join(`
|
|
19
|
+
`)}function ct(e){let t=[],s=e.split(`
|
|
20
20
|
`);for(let n=0;n<s.length;n++){let o=s[n].trim();/^(CREATE|ALTER|DROP|INSERT|UPDATE|DELETE|SELECT|WITH|GRANT|REVOKE|BEGIN|COMMIT)\b/i.test(o)&&t.push(`${n+1}: ${o.slice(0,120)}${o.length>120?"...":""}`)}return t.join(`
|
|
21
|
-
`)}import k from"fs";import
|
|
22
|
-
`),n=null;continue}a.add(
|
|
23
|
-
`).trim()||null}))}function
|
|
21
|
+
`)}import k from"fs";import Y from"path";function K(e){if(!e||typeof e!="string")return[];let t=e.split(/\r?\n/),s=!1,n=null,o=[],a=new Set;for(let c of t){if(/^##\s+Phases\s*$/i.test(c)){s=!0;continue}if(/^##\s+/.test(c)&&!/^###/.test(c)){n&&(o.push(n),n=null),s=!1;continue}if(!s)continue;let p=/^###\s+Phase\s+(\d+)\s*:\s*(.+?)\s*$/.exec(c);if(p){n&&o.push(n);let d=parseInt(p[1],10),i=p[2];if(a.has(d)){process.stderr.write(`[cairn] memo phase parser: duplicate Phase ${d} ignored
|
|
22
|
+
`),n=null;continue}a.add(d),n={phase_number:d,text:i,bodyLines:[]};continue}n&&n.bodyLines.push(c)}return n&&o.push(n),o.map(c=>({phase_number:c.phase_number,text:c.text,body:c.bodyLines.join(`
|
|
23
|
+
`).trim()||null}))}function ke(e,t,s){let n=e.prepare("SELECT id, phase_number, status FROM main.roadmap_phases WHERE decision_name = ? ORDER BY phase_number").all(t),o=new Map(n.map(r=>[r.phase_number,r])),a=new Set,c=e.prepare("UPDATE main.roadmap_phases SET text = ?, body = ?, status = CASE WHEN status = ? THEN ? ELSE status END WHERE id = ?"),p=e.prepare("INSERT INTO main.roadmap_phases (decision_name, phase_number, parent_phase_id, text, body, status, position) VALUES (?, ?, NULL, ?, ?, ?, ?)"),d=e.prepare("UPDATE main.roadmap_phases SET status = 'stale' WHERE id = ?"),i=[],u=[],m=[];for(let r=0;r<s.length;r++){let l=s[r];a.add(l.phase_number);let y=o.get(l.phase_number);if(y)c.run(l.text,l.body,"stale","open",y.id),i.push({id:y.id,phase_number:l.phase_number,text:l.text,reactivated:y.status==="stale"});else{let x=p.run(t,l.phase_number,l.text,l.body,"open",r);u.push({id:Number(x.lastInsertRowid),phase_number:l.phase_number,text:l.text})}}for(let[r,l]of o)!a.has(r)&&l.status!=="stale"&&l.status!=="done"&&(d.run(l.id),m.push({id:l.id,phase_number:r}));return{updated:i.length,inserted:u.length,staled:m.length,updated_phases:i,inserted_phases:u,staled_phases:m}}var P="roadmap",lt=`# Roadmap
|
|
24
24
|
|
|
25
25
|
The forward-looking plan: only upcoming and in-progress phases live here. When a
|
|
26
26
|
phase is marked done (cairn_roadmap set_status <id> done) it is removed from this
|
|
@@ -31,67 +31,72 @@ the plan \u2014 Cairn syncs it into the live tracker on the next cairn_roadmap r
|
|
|
31
31
|
|
|
32
32
|
### Phase 1: First phase title
|
|
33
33
|
What this phase delivers.
|
|
34
|
-
`;function
|
|
35
|
-
`),"utf8")}function
|
|
34
|
+
`;function H(){return Y.join(J(),"roadmap.md")}function pt(){return Y.join(J(),"roadmap_completed.md")}function ne(){let e=H();return k.existsSync(e)?k.readFileSync(e,"utf8"):""}function de(){let e=H();return k.existsSync(e)?!1:(k.writeFileSync(e,lt,"utf8"),!0)}function dt(e){let t=[];for(let s of e){let n=(s.text||"").trim();n&&(!Number.isInteger(s.phase_number)||s.phase_number<1||t.push({phase_number:s.phase_number,text:n,body:s.body??null}))}return t}var pe="decision_production_roadmap.md";function ut(e){let t=e.match(/^---\n[\s\S]*?\n---\n?/);return t?e.slice(t[0].length):e}function mt(e,t){let s=Y.join(e,"MEMORY.md");if(!k.existsSync(s))return;let n=k.readFileSync(s,"utf8").split(/\r?\n/).filter(o=>!o.includes(`](${t})`));k.writeFileSync(s,n.join(`
|
|
35
|
+
`),"utf8")}function ft(){let e=H();if(k.existsSync(e))return null;let t=[],s=we();s&&t.push(s),t.push(Y.join(J(),"memory"));let n=null,o=null;for(let c of t){let p=Y.join(c,pe);n==null&&k.existsSync(p)&&(n=ut(k.readFileSync(p,"utf8")).trim(),o=p)}if(n==null)return null;let a=/^#\s/m.test(n)?"":`# Roadmap
|
|
36
36
|
|
|
37
37
|
`;k.writeFileSync(e,a+n+`
|
|
38
|
-
`,"utf8");for(let
|
|
39
|
-
`).trim()||null})).filter(
|
|
38
|
+
`,"utf8");for(let c of t){let p=Y.join(c,pe);try{k.existsSync(p)&&k.unlinkSync(p)}catch{}try{mt(c,pe)}catch{}}return{migrated:!0,from:o,to:e}}function G(e){ft();let t=H();if(!k.existsSync(t))return null;let s=k.readFileSync(t,"utf8");if(!/^##\s+Phases\s*$/im.test(s))return null;let n=dt(K(s));return ke(e,P,n)}function ue(){let e=pt();return k.existsSync(e)?k.readFileSync(e,"utf8").split(/\r?\n/).filter(t=>/^-\s+\d{4}-\d{2}-\d{2}\s+—\s+Phase\s/.test(t)).length:0}import V from"fs";import me from"path";import{execSync as ht}from"child_process";var Re=120;function he(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>Re&&(t=t.slice(0,Re-1).trimEnd()+"\u2026"),t}function A(e){return String(e||"").toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function yt(e){if(!e||typeof e!="string")return[];let t=e.split(/\r?\n/),s=i=>i.map(u=>({text:he(u.titleRaw),body:u.bodyLines.join(`
|
|
39
|
+
`).trim()||null})).filter(u=>u.text),n=[],o=null;for(let i of t){let u=/^(#{1,6})\s+(.+?)\s*$/.exec(i);if(u&&u[1].length>=2&&u[1].length<=4){o&&n.push(o),o={titleRaw:u[2],bodyLines:[]};continue}o&&o.bodyLines.push(i)}o&&n.push(o);let a=[];o=null;for(let i of t){let u=/^(\d+)[.)]\s+(.+?)\s*$/.exec(i);if(u){o&&a.push(o),o={titleRaw:u[2],bodyLines:[]};continue}o&&o.bodyLines.push(i)}o&&a.push(o);let c=[s(n),s(a)].filter(i=>i.length>=2);if(c.length)return c.sort((i,u)=>u.length-i.length),c[0];let p=t.find(i=>i.trim());return[{text:he(p||"Plan")||"Plan",body:e.trim()||null}]}function gt(e){let t=[];return e.forEach((s,n)=>{t.push(`### Phase ${n+1}: ${s.text}`),s.body&&s.body.trim()&&t.push(s.body.trim()),t.push("")}),t.join(`
|
|
40
40
|
`).replace(/\n{3,}/g,`
|
|
41
41
|
|
|
42
42
|
`).trimEnd()+`
|
|
43
|
-
`}function
|
|
43
|
+
`}function ve(e){let t=ne(),s=t.split(/\r?\n/),n=s.findIndex(i=>/^##\s+Phases\s*$/i.test(i)),o=gt(e);if(n===-1){let i=t.replace(/\s*$/,"");V.writeFileSync(H(),`${i}
|
|
44
44
|
|
|
45
45
|
## Phases
|
|
46
46
|
|
|
47
|
-
${o}`,"utf8");return}let a=s.length;for(let
|
|
47
|
+
${o}`,"utf8");return}let a=s.length;for(let i=n+1;i<s.length;i++)if(/^##\s+/.test(s[i])&&!/^###/.test(s[i])){a=i;break}let c=s.slice(0,n+1).join(`
|
|
48
48
|
`),p=s.slice(a).join(`
|
|
49
|
-
`).replace(/^\n+/,""),
|
|
49
|
+
`).replace(/^\n+/,""),d=`
|
|
50
50
|
|
|
51
51
|
${o}${p.trim()?`
|
|
52
|
-
`+p:""}`;
|
|
53
|
-
`).filter(Boolean)}catch{p=[]}try{
|
|
54
|
-
`)
|
|
52
|
+
`+p:""}`;V.writeFileSync(H(),c+d,"utf8")}function Pe(e){let t=yt(e);if(t.length===0)return{added:[],skipped:[],total:0};let n=de()?[]:K(ne()).map(d=>({text:d.text,body:d.body})),o=new Set(n.map(d=>A(d.text))),a=[...n],c=[],p=[];for(let d of t){let i=A(d.text);if(o.has(i)){p.push(d.text);continue}o.add(i),a.push(d),c.push(d.text)}return c.length>0&&ve(a),{added:c,skipped:p,total:a.length}}function _t(e){return e==="completed"?"done":e==="in_progress"?"in_progress":"open"}function St(e){try{return e.prepare("SELECT phase_id FROM main.roadmap_cursor WHERE singleton = 1").get()?.phase_id??null}catch{return null}}function Oe(e,t){if(!Array.isArray(t)||t.length===0)return{changed:!1};let s=t.map(r=>({text:he(r.content||r.activeForm||""),status:_t(r.status)})).filter(r=>r.text);if(s.length===0)return{changed:!1};let n=e.prepare("SELECT id, status FROM main.roadmap_phases WHERE decision_name = ? AND parent_phase_id IS NULL").all(P).filter(r=>r.status!=="stale");if(n.length===0){let l=de()?[]:K(ne()).map(S=>({text:S.text,body:S.body})),y=new Set(l.map(S=>A(S.text))),x=[...l],f=0;for(let S of s){let w=A(S.text);y.has(w)||(y.add(w),x.push({text:S.text,body:null}),f++)}if(f===0)return{changed:!1};ve(x);let _=G(e);return{changed:!0,seeded:f,diff:_}}let o=St(e);o==null&&(o=n.find(r=>r.status==="in_progress")?.id??n.find(r=>r.status==="open")?.id??n[0].id);let a=e.prepare("SELECT id, text, status FROM main.roadmap_phases WHERE parent_phase_id = ?").all(o),c=new Map(a.map(r=>[A(r.text),r])),p=e.prepare("INSERT INTO main.roadmap_phases (decision_name, phase_number, parent_phase_id, text, status, position) VALUES (NULL, NULL, ?, ?, ?, ?)"),d=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,u=0,m=0;for(let r of s){let l=c.get(A(r.text));if(l){if(l.status==="done"&&r.status!=="done")continue;l.status!==r.status&&(d.run(r.status,l.id),m++)}else p.run(o,r.text,r.status,i++),u++}return{changed:u>0||m>0,parentId:o,inserted:u,updated:m}}var xt=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 wt(e){return[...new Set(A(e).split(" ").filter(t=>t.length>=4&&!xt.has(t)))]}function Et(e,t){if(!e||!t?.length)return null;let s=String(e),n=/\bphase\s*#?\s*(\d+)\b/i.exec(s);if(n){let c=parseInt(n[1],10),p=t.find(d=>d.phase_number===c);if(p)return{...p,confidence:"high"}}let o=new Set(A(s).split(" ").filter(Boolean)),a=null;for(let c of t){let p=wt(c.text);if(p.length<2)continue;let d=p.filter(u=>o.has(u)),i=d.length/p.length;d.length>=2&&i>=.6&&(!a||i>a.ratio)&&(a={...c,confidence:"medium",ratio:i})}return a?(delete a.ratio,a):null}function fe(e,t){return ht(`git ${t}`,{cwd:e,encoding:"utf8",timeout:5e3}).trim()}function je(e,t){let s=me.join(t,".cairn"),n=me.join(s,".last-commit"),o=me.join(s,"roadmap-pending.json"),a;try{a=fe(t,"rev-parse HEAD")}catch{return{candidates:[],newCommits:0}}let c=null;try{c=V.readFileSync(n,"utf8").trim()||null}catch{}let p=[];if(c&&c!==a)try{p=fe(t,`rev-list --no-merges --reverse ${c}..HEAD`).split(`
|
|
53
|
+
`).filter(Boolean)}catch{p=[]}try{V.writeFileSync(n,a,"utf8")}catch{}let d=[];try{let i=JSON.parse(V.readFileSync(o,"utf8"));Array.isArray(i)&&(d=i)}catch{}if(p.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(P);for(let u of p){let m="";try{m=fe(t,`show -s --format=%s%n%b ${u}`)}catch{}let r=Et(m,i);r&&!d.some(l=>l.phase_id===r.id)&&d.push({phase_id:r.id,phase_number:r.phase_number,text:r.text,commit:u.slice(0,7),confidence:r.confidence})}}if(d.length){let i=new Set(e.prepare("SELECT id FROM main.roadmap_phases WHERE status IN ('open','in_progress')").all().map(u=>u.id));d=d.filter(u=>i.has(u.phase_id))}try{V.writeFileSync(o,JSON.stringify(d),"utf8")}catch{}return{candidates:d,newCommits:p.length}}import F from"fs";import I from"path";var Te="cairn",Le=`<!-- ${Te}:roadmap -->`,bt=/^<!--\s*([A-Za-z0-9_.-]+)\s*:\s*roadmap\s*-->/;function $t(e){if(typeof e!="string")return null;let t=e.indexOf(`
|
|
54
|
+
`),s=(t===-1?e:e.slice(0,t)).trim(),n=bt.exec(s);return n?n[1].toLowerCase():null}var Fe="migrated-from";function kt(e){if(typeof e!="string")return null;let t=e.indexOf(`
|
|
55
|
+
`);if(t===-1)return null;let s=e.indexOf("-->",t),n=s===-1?e.slice(0,512):e.slice(t,s),o=new RegExp(`^\\s*${Fe}=(.+?)\\s*$`,"m").exec(n);return o?o[1]:null}var Rt={open:"open",in_progress:"in progress",done:"done",blocked:"blocked",stale:"stale"};function vt(e){return e==="done"?"x":e==="in_progress"?"~":e==="blocked"?"!":" "}function Ne(){return I.join(ee(),"ROADMAP.md")}function Pt(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){let t=new Map,s;try{s=e.prepare("SELECT blocker_id, blocked_id FROM main.roadmap_phase_deps").all()}catch{return t}for(let n of s)t.has(n.blocked_id)||t.set(n.blocked_id,new Set),t.get(n.blocked_id).add(n.blocker_id);return t}function jt(e,t){let s=e.decision_name??"",n=t.decision_name??"";return s!==n?s<n?-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 Me(e,t={}){let s=t.migratedFrom||null,n;try{n=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(n.filter(f=>f.status!=="stale").length===0)return null;let o=Pt(e),a=Ot(e),c=new Map(n.map(f=>[f.id,f.status])),p=new Map(n.map(f=>[f.id,f.phase_number!=null?`Phase ${f.phase_number}`:f.text])),d=f=>{let _=a.get(f);return _?[..._].filter(S=>c.get(S)!=="done").map(S=>p.get(S)||`#${S}`):[]},i=new Map;for(let f of n){let _=f.parent_phase_id??"root";i.has(_)||i.set(_,[]),i.get(_).push(f)}for(let f of i.values())f.sort(jt);let u=new Map;for(let f of i.get("root")||[])f.decision_name!=null&&(u.has(f.decision_name)||u.set(f.decision_name,[]),u.get(f.decision_name).push(f));let m=[...u.keys()].sort((f,_)=>f===P?-1:_===P?1:f<_?-1:f>_?1:0),r=[Le,"<!--"," 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."];s&&(r.push(" The ROADMAP.md that was here before cairn adopted this file is kept at:"),r.push(` ${Fe}=${s}`)),r.push("-->","","# Roadmap","","Legend: `[x]` done \xB7 `[~]` in progress \xB7 `[ ]` open \xB7 `[!]` blocked.");let l=(f,_)=>{let S=" ".repeat(_),w=f.phase_number!=null?`Phase ${f.phase_number}: ${f.text}`:f.text,R=Rt[f.status]||f.status,W=d(f.id);if(W.length&&(R+=` \xB7 waiting on ${W.join(", ")}`),o===f.id&&(R+=" \xB7 \u2190 current"),r.push(`${S}- [${vt(f.status)}] **${w}** \u2014 ${R}`),f.body){let T=f.body.split(`
|
|
56
|
+
`).map(X=>X.trim()).find(Boolean);T&&r.push(`${S} ${T}`)}for(let T of i.get(f.id)||[])T.status!=="stale"&&l(T,_+1)},y=!1;for(let f of m){let _=u.get(f).filter(w=>w.status!=="stale"),S=f===P?_.filter(w=>w.status!=="done"):_;if(S.length!==0){if(y=!0,r.push(""),f===P)r.push("## Active plan");else{let w=_.filter(R=>R.status==="done").length;r.push(`## ${f} \u2014 ${w}/${_.length} done`)}r.push("");for(let w of S)l(w,0)}}if(!y)return null;let x=ue();return x>0&&r.push("","---","",`**Shipped:** ${x} phase${x===1?"":"s"} \u2014 see \`.cairn/roadmap_completed.md\`.`),r.join(`
|
|
55
57
|
`)+`
|
|
56
|
-
`}function
|
|
57
|
-
`)
|
|
58
|
-
`).trim()||null}try{let
|
|
59
|
-
`))}return{active:!0,currentLabel:
|
|
60
|
-
`),process.exit(0)});var
|
|
61
|
-
`).length,
|
|
62
|
-
`).length,
|
|
63
|
-
${
|
|
58
|
+
`}function Mt(e){let t=I.join(e,"ROADMAP.bak.md");if(!F.existsSync(t))return t;for(let s=2;s<=1e3;s++){let n=I.join(e,`ROADMAP.bak.${s}.md`);if(!F.existsSync(n))return n}return null}function Tt(e,t){let s=I.join(I.dirname(e),`.${I.basename(e)}.${process.pid}.tmp`);try{F.writeFileSync(s,t,"utf8"),F.renameSync(s,e)}catch(n){try{F.unlinkSync(s)}catch{}throw n}}function C(e,t,s={}){return{written:!1,reason:e,warning:`[cairn] ROADMAP.md was not updated \u2014 ${e}`,path:t,...s}}function De(e){let t=Ne(),s=null;if(F.existsSync(t))try{s=F.readFileSync(t,"utf8")}catch(i){return C(`the existing file could not be read (${i.message})`,t)}let n=$t(s),o=s!=null&&(n===Te||s.startsWith(Le));if(s!=null&&n!=null&&!o)return{written:!1,reason:`ROADMAP.md is generated by another provider (${n}) \u2014 refusing to overwrite`,conflict_provider:n,warning:`[cairn] ROADMAP.md carries the "${n}:roadmap" marker, 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 a=Me(e,{migratedFrom:o?kt(s):null});if(a==null){if(o)try{return F.unlinkSync(t),{written:!1,removed:!0,path:t}}catch(i){return C(`the stale projection could not be removed (${i.message})`,t)}return{written:!1,reason:"empty roadmap \u2014 no file written",path:t}}if(o&&s===a)return{written:!1,unchanged:!0,path:t,bytes:Buffer.byteLength(a)};let c=null,p=null;if(s!=null&&!o){let i=Mt(I.dirname(t));if(i==null)return C("no free ROADMAP.bak name was available to preserve the existing file",t);try{F.renameSync(t,i)}catch(u){return C(`the existing file could not be preserved (${u.message})`,t)}c=I.basename(i),p=i,a=Me(e,{migratedFrom:c})}try{Tt(t,a)}catch(i){if(p)try{return F.renameSync(p,t),C(`write failed (${i.message}); the original ROADMAP.md was restored`,t)}catch{return C(`write failed (${i.message}); the original ROADMAP.md is at ${c} and must be restored by hand`,t,{backed_up_to:c})}return C(`write failed (${i.message})`,t)}let d={written:!0,path:t,bytes:Buffer.byteLength(a)};return c&&(d.backed_up_to=c,d.warning=`[cairn] The existing ROADMAP.md was not cairn-generated. It has been preserved as ${c}, and ROADMAP.md is now generated from cairn's roadmap.`),d}function Lt(e){try{return De(e)}catch(t){process.stderr.write(`[cairn] ROADMAP.md publish skipped: ${t.message}
|
|
59
|
+
`);let s=null;try{s=Ne()}catch{}return C(`publish failed (${t.message})`,s)}}function se(e){let t=Lt(e);return t&&t.warning?t.warning:null}var Ft=new Set(["open","in_progress"]);function Nt(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 Dt(e,t){let s=e.prepare("SELECT parent_phase_id, status FROM main.roadmap_phases WHERE id = ?"),n=e.prepare("UPDATE main.roadmap_phases SET status = 'in_progress' WHERE id = ? AND status = 'open'"),o=s.get(t);for(;o&&o.parent_phase_id!=null;)n.run(o.parent_phase_id),o=s.get(o.parent_phase_id)}function Ae(e,t){Nt(e,t),e.prepare("UPDATE main.roadmap_phases SET status = 'in_progress' WHERE id = ? AND status = 'open'").run(t),Dt(e,t)}function At(e){let t=new Map,s;try{s=e.prepare("SELECT blocker_id, blocked_id FROM main.roadmap_phase_deps").all()}catch{return t}for(let n of s)t.has(n.blocked_id)||t.set(n.blocked_id,new Set),t.get(n.blocked_id).add(n.blocker_id);return t}function Ct(e,t,s){let n=t.get(e);if(!n||n.size===0)return[];let o=[];for(let a of n)s.get(a)!=="done"&&o.push(a);return o}function Ce(e,t){let s=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(s.length===0)return{id:null,reason:"No phases \u2014 add a ## Phases section to .cairn/roadmap.md."};let n=new Map(s.map(m=>[m.id,m.status])),o=At(e),a=new Map;for(let m of s){let r=m.parent_phase_id??`root:${m.decision_name}`;a.has(r)||a.set(r,[]),a.get(r).push(m)}for(let m of a.values())m.sort((r,l)=>r.phase_number!=null&&l.phase_number!=null?r.phase_number-l.phase_number:r.position-l.position||r.id-l.id);let c=[],p=new Set;for(let m of s){if(m.parent_phase_id!=null||p.has(m.decision_name))continue;p.add(m.decision_name);let r=[],l=a.get(`root:${m.decision_name}`)||[];for(let y=l.length-1;y>=0;y--)r.push(l[y]);for(;r.length;){let y=r.pop();c.push(y);let x=a.get(y.id)||[];for(let f=x.length-1;f>=0;f--)r.push(x[f])}}let d=m=>Ft.has(m.status),i=[],u=0;if(t!=null){let m=c.findIndex(r=>r.id===t);u=m===-1?0:m+1}for(let m=u;m<c.length;m++){let r=c[m];if(!d(r))continue;let l=Ct(r.id,o,n);if(l.length>0){i.push({id:r.id,blockers:l});continue}let y=t!=null?s.find(_=>_.id===t):null,x=y&&y.decision_name!==r.decision_name,f;return t==null?f=`First actionable phase: ${r.decision_name??"(sub-task)"} / Phase ${r.phase_number??"\xB7"}.`:x?f=`Previous decision "${y.decision_name}" is complete \u2014 advanced to "${r.decision_name}".`:f=`Next open phase in "${r.decision_name??"(sub-task)"}" after id ${t}.`,i.length>0&&(f+=` Skipped ${i.length} dep-blocked phase(s): ${i.map(_=>`id ${_.id} (blocked by ${_.blockers.join(",")})`).join("; ")}.`),{id:r.id,reason:f,skipped_blocked:i}}return i.length>0?{id:null,reason:`All remaining open phases are blocked by unfinished dependencies: ${i.map(m=>`id ${m.id} (blocked by ${m.blockers.join(",")})`).join("; ")}.`,skipped_blocked:i}:{id:null,reason:"No actionable phases remaining."}}var It=new Set(["java","typescript","javascript","vue","python","sql"]);function Ue(e){let t=g.join(q.homedir(),".claude","projects",ie(e));return h.existsSync(t)?g.join(t,"memory"):null}function He(e){try{return h.readdirSync(e).filter(t=>t.endsWith(".md"))}catch{return[]}}function Wt(e){let t=Ue(e);if(!t||!h.existsSync(t))return 0;let s=g.join(e,".cairn","memory");h.mkdirSync(s,{recursive:!0});let n=0;for(let o of He(t)){let a=g.join(t,o),c;try{c=h.statSync(a)}catch{continue}if(!c.isFile())continue;let p=g.join(s,o),d=!h.existsSync(p);if(!d)try{d=c.mtimeMs>h.statSync(p).mtimeMs}catch{d=!0}if(d){h.copyFileSync(a,p);try{h.utimesSync(p,c.atime,c.mtime)}catch{}n++}}return n}function Ut(e){let t=Ue(e);if(!t||(h.mkdirSync(t,{recursive:!0}),He(t).some(o=>o!=="MEMORY.md")))return 0;let s=g.join(e,".cairn","memory");if(!h.existsSync(s))return 0;let n=0;for(let o of h.readdirSync(s)){let a=g.join(s,o),c;try{c=h.statSync(a)}catch{continue}if(c.isFile()){h.copyFileSync(a,g.join(t,o));try{h.utimesSync(g.join(t,o),c.atime,c.mtime)}catch{}n++}}return n}async function Ie(e){let t={active:!1},s=g.join(e,"index.db");if(!h.existsSync(s))return t;let n;try{({DatabaseSync:n}=await import("node:sqlite"))}catch{return t}let o;try{o=new n(s,{readonly:!0})}catch{return t}let a=p=>p.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");function c(p,d){if(!h.existsSync(p))return null;let i=h.readFileSync(p,"utf8"),u=!1,m=!1,r=[];for(let l of i.split(/\r?\n/)){if(/^##\s+Phases\s*$/i.test(l)){u=!0;continue}if(u&&/^##\s+/.test(l)&&!/^###/.test(l))break;if(!u)continue;let y=/^###\s+Phase\s+(\d+)\s*:\s*(.+?)\s*$/.exec(l);if(y){if(m)break;parseInt(y[1],10)===d&&(r.push(`### Phase ${y[1]}: ${y[2]}`),m=!0);continue}m&&r.push(l)}return r.join(`
|
|
60
|
+
`).trim()||null}try{let d=o.prepare("SELECT phase_id FROM roadmap_cursor WHERE singleton = 1").get()?.phase_id??null;if(d==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(),u={open:"[ ]",in_progress:"[~]",done:"[x]",blocked:"[!]",stale:"[s]"},m=new Map;for(let $ of i){let E=$.parent_phase_id??"root";m.has(E)||m.set(E,[]),m.get(E).push($)}for(let $ of m.values())$.sort((E,b)=>E.decision_name&&b.decision_name&&E.decision_name!==b.decision_name?E.decision_name.localeCompare(b.decision_name):E.phase_number!=null&&b.phase_number!=null?E.phase_number-b.phase_number:E.position-b.position||E.id-b.id);let r=m.get("root")||[],l=new Map;for(let $ of r)$.decision_name!=null&&(l.has($.decision_name)||l.set($.decision_name,[]),l.get($.decision_name).push($));let y=[],x=($,E)=>{for(let b of m.get($)||[]){if(b.status==="stale")continue;let oe=d===b.id?" \u2192":"",re=b.phase_number!=null?`Phase ${b.phase_number}: ${b.text}`:b.text;y.push(`${" ".repeat(E)}${u[b.status]||"[?]"}${oe} ${re}`),x(b.id,E+1)}};for(let[$,E]of l){let b=E.filter(v=>v.status!=="stale");if(b.length===0)continue;let oe=b.every(v=>v.status==="done"),re=b.some(v=>v.status==="in_progress"),Je=oe?"done":re?"in_progress":"open",Be=b.filter(v=>v.status==="done").length,Ye=$===P?"Roadmap":`Decision: ${$}`;y.push(`${u[Je]} ${Ye} (${Be}/${b.length} done)`);for(let v of E){if(v.status==="stale"||$===P&&v.status==="done")continue;let Ge=d===v.id?" \u2192":"";y.push(` ${u[v.status]||"[?]"}${Ge} Phase ${v.phase_number}: ${v.text}`),x(v.id,2)}}let f=$=>i.find(E=>E.id===$),_=f(d),S=_?.decision_name??null,w=_?.phase_number??null,R=_;for(;R&&R.parent_phase_id!=null&&(R=f(R.parent_phase_id),!!R);)S=R.decision_name??S,w=R.phase_number??w;o.close();let W=_?_.phase_number!=null?`${_.decision_name} / Phase ${_.phase_number}: ${_.text}`:`${S} / Phase ${w} \u2192 ${_.text}`:"(unknown)",T=g.join(e,".last-roadmap-cursor"),X=null;try{X=parseInt(h.readFileSync(T,"utf8").trim(),10)}catch{}let ge=X!==d;try{h.writeFileSync(T,String(d),"utf8")}catch{}let _e=null;if(ge&&S!=null&&w!=null){let $=S===P?g.join(e,"roadmap.md"):g.join(e,"memory",`decision_${a(S)}.md`),E=c($,w);E&&(_e=E.split(`
|
|
61
|
+
`))}return{active:!0,currentLabel:W,treeLines:y,advanced:ge,memoLines:_e}}catch{try{o?.close()}catch{}return t}}process.on("uncaughtException",e=>{process.stderr.write(`cairn: ${e.message}
|
|
62
|
+
`),process.exit(0)});var O=process.argv[2];if(O==="--version"||O==="-v"){let e=JSON.parse(h.readFileSync(new URL("../package.json",import.meta.url),"utf8"));console.log(e.version),process.exit(0)}else if(O==="minify"){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{let t,s;try{s=JSON.parse(e)?.tool_input||{},t=s.file_path}catch{process.exit(0)}t||process.exit(0),(s.offset!=null||s.limit!=null)&&process.exit(0),t=g.resolve(t);let n=ce(t);n||process.exit(0);let o=g.join(n,"views"),a=g.relative(o,t);!a.startsWith("..")&&!g.isAbsolute(a)&&process.exit(0);let c=U(n),d=te(n,c)>0,i=c[t];i?.state==="edit-ready"&&(d&&M(n,c),process.exit(0)),i?.state==="compressed"&&(i.state="edit-ready",M(n,c),process.exit(0));let u=g.extname(t).toLowerCase(),m=Se[u];(!m||!It.has(m))&&(d&&M(n,c),process.exit(0));let r;try{r=h.readFileSync(t,"utf8")}catch{d&&M(n,c),process.exit(0)}let l=r.split(`
|
|
63
|
+
`).length,y=m==="vue"?xe(r):Q(r,m),x=y.split(`
|
|
64
|
+
`).length,f=l>0?Math.round((1-x/l)*100):0,_=be(n,t);h.mkdirSync(g.dirname(_),{recursive:!0}),h.writeFileSync(_,y,"utf8");let S=i?.readCount??0;c[t]={tempPath:_,state:"compressed",minifiedAt:h.statSync(t).mtimeMs,readCount:S+1},M(n,c);let w=x>Ee,R=S>0;if(R||w){let W=$e(y,m),T=R?`[cairn: ${l} \u2192 ${x} lines | seen \xD7${S+1} this session]`:`[cairn: ${l} \u2192 outline (${x} minified lines)]`;process.stderr.write(`${T}
|
|
65
|
+
${W}
|
|
64
66
|
Full minified view: Read("${_}")
|
|
65
|
-
`)}else process.stderr.write(`[cairn: ${l} \u2192 ${
|
|
66
|
-
${
|
|
67
|
+
`)}else process.stderr.write(`[cairn: ${l} \u2192 ${x} lines (-${f}%)]
|
|
68
|
+
${y}
|
|
67
69
|
Cached view: Read("${_}")
|
|
68
|
-
`);process.exit(2)})}else if(
|
|
70
|
+
`);process.exit(2)})}else if(O==="edit-guard"){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{let t="(unknown)",s="Edit";try{let m=JSON.parse(e);t=m?.tool_input?.file_path||"(unknown)",s=m?.tool_name||"Edit"}catch{}let n=g.resolve(t),o=ce(n);o||process.exit(0);let a=g.join(o,"views"),c=g.relative(a,n);if(!c.startsWith("..")&&!g.isAbsolute(c)){let m=U(o),r=Object.entries(m).find(([,y])=>y.tempPath===n),l=r?`Edit the source file instead: Edit("${r[0]}")`:"Edit the original source file, not the .cairn/views/ cache.";process.stderr.write(`[cairn] Cannot edit a cached view file \u2014 it is read-only and will be overwritten on next read.
|
|
69
71
|
${l}
|
|
70
|
-
`),process.exit(2)}let p=
|
|
71
|
-
`).length<=300&&(m
|
|
72
|
+
`),process.exit(2)}let p=U(o),d=te(o,p),i=p[n];i||(d>0&&M(o,p),process.exit(0)),s==="Write"&&(delete p[n],M(o,p),process.exit(0)),i.state==="edit-ready"&&(delete p[n],M(o,p),process.exit(0)),i.state="edit-ready",M(o,p);let u=null;try{let m=h.readFileSync(n,"utf8");m.split(`
|
|
73
|
+
`).length<=300&&(u=m)}catch{}u!==null?process.stderr.write(`[cairn] File was compressed in context. Full source content:
|
|
72
74
|
|
|
73
|
-
${
|
|
75
|
+
${u}
|
|
74
76
|
|
|
75
77
|
Re-apply your Edit using the exact content above (state is now edit-ready).
|
|
76
|
-
`):process.stderr.write(`[cairn] File compressed. Steps: (1) Read("${
|
|
77
|
-
`),process.exit(2)})}else if(
|
|
78
|
-
`);try{
|
|
79
|
-
`),process.exit(0)}else if(
|
|
80
|
-
`)}}catch{}if(
|
|
81
|
-
|
|
82
|
-
`):
|
|
83
|
-
|
|
84
|
-
`)
|
|
85
|
-
`)
|
|
86
|
-
`)
|
|
87
|
-
`)
|
|
88
|
-
`).join("
|
|
89
|
-
`).
|
|
78
|
+
`):process.stderr.write(`[cairn] File compressed. Steps: (1) Read("${i.tempPath}") \u2014 loads full content into context. (2) Edit("${t}") \u2014 edit the original source, not the view.
|
|
79
|
+
`),process.exit(2)})}else if(O==="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 s=t?.tool_name||"",n=t?.tool_input||{},o=process.cwd(),a=g.join(o,".cairn");h.existsSync(a)||process.exit(0);let c=g.join(a,"index.db");h.existsSync(c)||process.exit(0);let p;try{({DatabaseSync:p}=await import("node:sqlite"))}catch{process.exit(0)}let d=/exit.?plan.?mode/i.test(s),i=/todo.?write/i.test(s);!d&&!i&&process.exit(0);let u=null,m;try{if(d){let l=n.plan;(typeof l!="string"||!l.trim())&&process.exit(0);let y=Pe(l);if(m=new p(c),G(m),(m.prepare("SELECT phase_id FROM main.roadmap_cursor WHERE singleton = 1").get()?.phase_id??null)==null){let f=Ce(m,null);f.id!=null&&Ae(m,f.id)}y.added.length>0&&(u=`[cairn] roadmap: captured ${y.added.length} phase(s) from plan${y.skipped.length?` (${y.skipped.length} already present)`:""}.`)}else if(i){m=new p(c);let l=Oe(m,n.todos);l.seeded?u=`[cairn] roadmap: seeded ${l.seeded} phase(s) from todos.`:l.inserted>0&&(u=`[cairn] roadmap: linked ${l.inserted} new sub-task(s) to the current phase.`)}}catch(l){process.stderr.write(`[cairn] roadmap-capture skipped: ${l.message}
|
|
80
|
+
`);try{m?.close()}catch{}process.exit(0)}let r=m?se(m):null;try{m?.close()}catch{}r&&(u=u?`${u} ${r}`:r),u&&process.stdout.write(JSON.stringify({systemMessage:u})),process.exit(0)})}else if(O==="validate-map"){let e=g.join(process.cwd(),".cairn");h.existsSync(e)||process.exit(0);let t=U(e),s=te(e,t);for(let n of Object.values(t))n.readCount=0;M(e,t),s>0&&process.stdout.write(`[cairn] Cleaned minify map: ${s} stale entr${s===1?"y":"ies"} removed
|
|
81
|
+
`),process.exit(0)}else if(O==="checkpoint"&&process.argv[3]==="--auto"){let e=`Auto-checkpoint at ${new Date().toISOString()}`,t=[],s=[];try{let n=g.join(process.cwd(),".cairn"),o=g.join(n,"session.json");h.existsSync(o)&&(t=JSON.parse(h.readFileSync(o,"utf8")).notes||[]);let a=U(n);s=Object.entries(a).filter(([,c])=>(c.readCount??0)>0).map(([c])=>c)}catch{}ae(null,{message:e,active_files:s,notes:t}),process.exit(0)}else if(O==="session-tick"){let e=process.cwd(),t=g.join(e,".cairn");h.existsSync(t)||process.exit(0);let s=[];try{let p=`Auto-checkpoint at ${new Date().toISOString()}`,d=[],i=g.join(t,"session.json");if(h.existsSync(i))try{d=JSON.parse(h.readFileSync(i,"utf8")).notes||[]}catch{}let u=U(t),m=Object.entries(u).filter(([,r])=>(r.readCount??0)>0).map(([r])=>r);ae(null,{message:p,active_files:m,notes:d}),s.push("\u2713 checkpoint saved")}catch{}try{let p=Wt(e);p>0&&s.push(`memory backed up (${p})`)}catch{}let n=[],o=null;try{let p=g.join(t,"index.db");if(h.existsSync(p)){let{DatabaseSync:d}=await import("node:sqlite"),i=new d(p);try{G(i),o=se(i);try{n=je(i,e).candidates}catch{}}finally{i.close()}}}catch{}let a="";try{let p=await Ie(t);if(p.active){s.push(`roadmap ${p.advanced?"updated":"on track"}: ${p.currentLabel}`);let d=["[cairn] Production roadmap (\u2192 = cursor / current phase):",...p.treeLines.map(i=>" "+i)];p.memoLines&&d.push("","\u2500\u2500 Current phase detail (from roadmap.md) \u2500\u2500",...p.memoLines,"\u2500\u2500 (re-read after each phase to confirm direction) \u2500\u2500"),d.push("","Keep this current via cairn_roadmap on MATERIAL change (phase done / blocked / new) \u2014 not every turn."),a=d.join(`
|
|
82
|
+
`)}}catch{}if(o&&(s.push("ROADMAP.md not updated \u2014 see warning"),a=a?`${a}
|
|
83
|
+
|
|
84
|
+
${o}`:o),n.length>0){s.push(`${n.length} phase(s) may be done \u2014 confirm with user`);let p=["","[cairn] Possible COMPLETED phase(s) detected from recent commits \u2014","CONFIRM WITH THE USER before marking done; do NOT mark done unilaterally:"];for(let d of n)p.push(` \u2022 Phase ${d.phase_number}: ${d.text} (commit ${d.commit}, ${d.confidence}) \u2192 if confirmed: cairn_roadmap set_status ${d.phase_id} done`);a=a?a+`
|
|
85
|
+
`+p.join(`
|
|
86
|
+
`):p.join(`
|
|
87
|
+
`).trimStart()}s.length===0&&process.exit(0);let c={systemMessage:`[cairn] ${s.join(" \xB7 ")}`};a&&(c.additionalContext=a),process.stdout.write(JSON.stringify(c)),process.exit(0)}else if(O==="memory-restore"){let e=process.cwd();h.existsSync(g.join(e,".cairn"))||process.exit(0);try{let t=Ut(e);t>0&&process.stdout.write(`[cairn] Restored ${t} memory file(s) from .cairn/memory backup (Claude store was empty)
|
|
88
|
+
`)}catch{}process.exit(0)}else if(O==="resume-hint"){let e=g.join(process.cwd(),".cairn"),t=g.join(e,"session.json"),s=g.join(e,"index.db"),n=g.join(e,".hint-lock"),o=1800*1e3,a=process.cwd()===q.homedir();if(!a&&h.existsSync(e)&&(h.existsSync(s)||h.existsSync(t))){let r=g.join(e,".cairn-project");if(!h.existsSync(r))try{h.writeFileSync(r,"","utf8"),process.stdout.write(`[cairn] Repaired: wrote .cairn-project sentinel for hook compatibility.
|
|
89
|
+
`)}catch{}}if(!a&&h.existsSync(s))try{let{DatabaseSync:r}=await import("node:sqlite"),l=new r(s,{readonly:!0}),y=null;try{y=se(l)}finally{l.close()}y&&process.stdout.write(`${y}
|
|
90
|
+
`)}catch{}{let r=[g.join(process.cwd(),".claude","settings.json"),g.join(q.homedir(),".claude","settings.json")];for(let l of r)try{if(!h.existsSync(l))continue;let y=h.readFileSync(l,"utf8"),x=JSON.parse(y),f=x?.hooks?.PreToolUse;if(!Array.isArray(f))continue;let _=!1;for(let S of f)if(!(S.matcher!=="Edit"||!Array.isArray(S.hooks)))for(let w of S.hooks)w.command==="cairn set-mode edit"&&(w.command="cairn edit-guard",_=!0);_&&(h.writeFileSync(l,JSON.stringify(x,null,2),"utf8"),process.stdout.write(`[cairn] Repaired: migrated cairn set-mode \u2192 cairn edit-guard in ${l}
|
|
91
|
+
`))}catch{}}let c="";try{c=(JSON.parse(h.readFileSync("/dev/stdin","utf8"))?.prompt||"").toLowerCase()}catch{}let d=/\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(c);h.existsSync(t)||(h.existsSync(s)||(h.existsSync(n)&&Date.now()-h.statSync(n).mtimeMs<o&&process.exit(0),h.mkdirSync(e,{recursive:!0}),h.writeFileSync(n,new Date().toISOString(),"utf8"),process.stdout.write(`[cairn] No index found. Run cairn_maintain to index this project.
|
|
92
|
+
`)),process.exit(0)),h.existsSync(n)&&Date.now()-h.statSync(n).mtimeMs<o&&process.exit(0);let i=JSON.parse(h.readFileSync(t,"utf8")),u=new Date(i.checkpoint_at).toLocaleString(),m=[`[cairn] Prior session: "${i.message}" (${u}).`,"[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 call cairn_checkpoint with message + active_files + notes.","[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(d){let r=["[cairn] RESUME \u2014 checkpoint loaded inline:"];r.push(` message: ${i.message}`),r.push(` checkpoint: ${u}`),i.active_files?.length>0&&r.push(` active_files: ${i.active_files.join(", ")}`),i.notes?.length>0&&r.push(` notes: ${i.notes.join(" | ")}`);try{let l=new Date(i.checkpoint_at).toISOString(),y=ye(`git log --oneline --after="${l}"`,{cwd:process.cwd(),encoding:"utf8",timeout:5e3}).trim();r.push(` commits_since: ${y?y.split(`
|
|
93
|
+
`).join("; "):"(none)"}`)}catch{}try{let l=ye("git diff --name-only HEAD",{cwd:process.cwd(),encoding:"utf8",timeout:5e3}).trim();l&&r.push(` uncommitted: ${l.split(`
|
|
94
|
+
`).join(", ")}`)}catch{}try{let l=ye("git status --short",{cwd:process.cwd(),encoding:"utf8",timeout:5e3}).trim();l&&r.push(` git_status:
|
|
90
95
|
${l.split(`
|
|
91
|
-
`).map(
|
|
92
|
-
`)}`)}catch{}r.push(" \u2192 Call cairn_resume for full index status and open todos."),
|
|
93
|
-
`))}process.stdout.write(
|
|
96
|
+
`).map(y=>" "+y).join(`
|
|
97
|
+
`)}`)}catch{}r.push(" \u2192 Call cairn_resume for full index status and open todos."),m.push(r.join(`
|
|
98
|
+
`))}process.stdout.write(m.join(`
|
|
94
99
|
`)+`
|
|
95
|
-
`),h.writeFileSync(n,new Date().toISOString(),"utf8"),process.exit(0)}else if(
|
|
100
|
+
`),h.writeFileSync(n,new Date().toISOString(),"utf8"),process.exit(0)}else if(O==="roadmap-hint"){let e=g.join(process.cwd(),".cairn"),t=await Ie(e);t.active||process.exit(0);let s=["[cairn] ROADMAP \u2014 cursor is active.",...t.treeLines.map(n=>"[cairn] "+n),`[cairn] Current: ${t.currentLabel}`];if(t.memoLines){s.push("[cairn] \u2500\u2500\u2500\u2500\u2500 Decision memo (current phase) \u2500\u2500\u2500\u2500\u2500");for(let n of t.memoLines)s.push("[cairn] "+n);s.push("[cairn] \u2500\u2500\u2500\u2500\u2500 (re-read after each phase to confirm direction) \u2500\u2500\u2500\u2500\u2500")}s.push("[cairn] Use cairn_roadmap set_status <id> done (auto-advances), focus <id>, or next to move cursor."),process.stdout.write(s.join(`
|
|
96
101
|
`)+`
|
|
97
|
-
`),process.exit(0)}else if(
|
|
102
|
+
`),process.exit(0)}else if(O==="install"){let e=process.platform,t=g.join(q.homedir(),".claude.json"),s={};if(h.existsSync(t))try{s=JSON.parse(h.readFileSync(t,"utf8"))}catch{}s.mcpServers=s.mcpServers||{};let n=!!s.mcpServers.cairn;s.mcpServers.cairn={command:"cairn-mcp"},h.writeFileSync(t,JSON.stringify(s,null,2),"utf8");let o=g.join(q.homedir(),".claude");We(o,!0),console.log("Cairn installed successfully!"),console.log(""),console.log(` Platform : ${e}`),console.log(` MCP : cairn-mcp registered in ${t}${n?" (updated)":""}`),console.log(` Hooks : installed in ${g.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(""),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(O==="install-hooks"){let e=process.argv.includes("--global"),t=e?g.join(q.homedir(),".claude"):g.join(process.cwd(),".claude");We(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)"),process.exit(0)}else console.error("Usage: cairn <--version | install | install-hooks [--global] | minify | edit-guard | validate-map | checkpoint --auto | session-tick | resume-hint | roadmap-hint | roadmap-capture | memory-restore>"),process.exit(1);function We(e,t){let s=g.join(e,"settings.json"),n={};if(h.existsSync(s))try{n=JSON.parse(h.readFileSync(s,"utf8"))}catch{}n.hooks=n.hooks||{};let o=n.hooks.PreToolUse||[];o.some(r=>r.matcher==="Read"&&r.hooks?.some(l=>l.command==="cairn minify"))||o.push({matcher:"Read",hooks:[{type:"command",command:"cairn minify"}]});let a=o.filter(r=>!(r.matcher==="Edit"&&r.hooks?.some(l=>l.command==="cairn set-mode edit")));a.some(r=>r.matcher==="Edit"&&r.hooks?.some(l=>l.command==="cairn edit-guard"))||a.push({matcher:"Edit",hooks:[{type:"command",command:"cairn edit-guard"}]}),a.some(r=>r.matcher==="Write"&&r.hooks?.some(l=>l.command==="cairn edit-guard"))||a.push({matcher:"Write",hooks:[{type:"command",command:"cairn edit-guard"}]}),n.hooks.PreToolUse=a;let c=(r,l)=>(r||[]).map(y=>({...y,hooks:(y.hooks||[]).filter(x=>!l(x.command))})).filter(y=>(y.hooks||[]).length>0),p=r=>typeof r=="string"&&/sync-memory-(forward|restore)\.(mjs|py)/.test(r),d=c(n.hooks.Stop,r=>r==="cairn checkpoint --auto"||r==="cairn roadmap-hint");d.some(r=>r.hooks?.some(l=>l.command==="cairn session-tick"))||d.push({hooks:[{type:"command",command:"cairn session-tick"}]}),n.hooks.Stop=d;let i=c(n.hooks.UserPromptSubmit,p);i.some(r=>r.hooks?.some(l=>l.command==="cairn resume-hint"))||i.push({hooks:[{type:"command",command:"cairn resume-hint"}]}),i.some(r=>r.hooks?.some(l=>l.command==="cairn memory-restore"))||i.push({hooks:[{type:"command",command:"cairn memory-restore"}]}),n.hooks.UserPromptSubmit=i;let u=c(n.hooks.PostToolUse,p),m=r=>{u.some(l=>l.matcher===r&&l.hooks?.some(y=>y.command==="cairn roadmap-capture"))||u.push({matcher:r,hooks:[{type:"command",command:"cairn roadmap-capture"}]})};if(m("ExitPlanMode"),m("TodoWrite"),n.hooks.PostToolUse=u,t){let r=g.join(e,"scripts");for(let l of["sync-memory-forward.mjs","sync-memory-restore.mjs","sync-memory-forward.py","sync-memory-restore.py"]){let y=g.join(r,l);if(h.existsSync(y))try{h.unlinkSync(y)}catch{}}}if(!t){let r=g.join(process.cwd(),".cairn");h.mkdirSync(r,{recursive:!0});let l=g.join(r,".cairn-project");h.existsSync(l)||h.writeFileSync(l,"","utf8")}h.mkdirSync(e,{recursive:!0}),h.writeFileSync(s,JSON.stringify(n,null,2),"utf8")}
|