@codrihub/memora 1.2.3 → 1.3.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/assets/app.js CHANGED
@@ -262,24 +262,24 @@
262
262
  .sk-li:first-child{border-top:0}
263
263
  @keyframes sk-breathe{0%,100%{opacity:1}50%{opacity:.45}}
264
264
  @media (prefers-reduced-motion:reduce){.sk{animation:none}}
265
- `,At=(n,e=12,t="")=>`<span class="sk${t?" "+t:""}" style="width:${n};height:${e}px"></span>`,_l=n=>n.map(e=>`<span class="sk sk-line" style="width:${e}%"></span>`).join("");function bA(){return at("skeleton-css",Td),`<div class="sk-reader" aria-busy="true" aria-label="Loading the node" style="display:flex;flex-direction:column;height:100%">
266
- <header class="vx-rbar">${At("28px",28,"r")}${At("48px")}<span style="width:10px"></span>${At("64px")}<span style="width:10px"></span>${At("110px")}
267
- <span class="vx-grow"></span>${At("28px",28)}${At("28px",28)}${At("64px",30)}${At("28px",28)}</header>
265
+ `,Tt=(n,e=12,t="")=>`<span class="sk${t?" "+t:""}" style="width:${n};height:${e}px"></span>`,_l=n=>n.map(e=>`<span class="sk sk-line" style="width:${e}%"></span>`).join("");function bA(){return at("skeleton-css",Td),`<div class="sk-reader" aria-busy="true" aria-label="Loading the node" style="display:flex;flex-direction:column;height:100%">
266
+ <header class="vx-rbar">${Tt("28px",28,"r")}${Tt("48px")}<span style="width:10px"></span>${Tt("64px")}<span style="width:10px"></span>${Tt("110px")}
267
+ <span class="vx-grow"></span>${Tt("28px",28)}${Tt("28px",28)}${Tt("64px",30)}${Tt("28px",28)}</header>
268
268
  <div class="vx-note-scroll"><div class="vx-page">
269
- <aside class="vx-rail">${At("90px",10)}${_l([70,55,62,48,58])}</aside>
269
+ <aside class="vx-rail">${Tt("90px",10)}${_l([70,55,62,48,58])}</aside>
270
270
  <div class="vx-col">
271
- ${At("min(420px,70%)",34)}
272
- <div class="sk-row" style="margin:14px 0 30px">${At("84px",20,"pill")}${At("120px",12)}${At("70px",12)}${At("64px",22,"pill")}${At("80px",22,"pill")}</div>
271
+ ${Tt("min(420px,70%)",34)}
272
+ <div class="sk-row" style="margin:14px 0 30px">${Tt("84px",20,"pill")}${Tt("120px",12)}${Tt("70px",12)}${Tt("64px",22,"pill")}${Tt("80px",22,"pill")}</div>
273
273
  ${_l([96,92,98,60])}
274
- <div class="sk-gap"></div>${At("34%",22)}
275
- <div class="sk-bullet">${At("6px",6,"r")}${At("62%")}</div>
276
- <div class="sk-bullet">${At("6px",6,"r")}${At("48%")}</div>
277
- <div class="sk-bullet">${At("6px",6,"r")}${At("55%")}</div>
278
- <div class="sk-gap"></div>${At("28%",22)}
279
- <div class="sk-table">${[0,1,2,3].map(()=>`<div>${At("70%")}${At("55%")}${At("62%")}${At("80%")}</div>`).join("")}</div>
274
+ <div class="sk-gap"></div>${Tt("34%",22)}
275
+ <div class="sk-bullet">${Tt("6px",6,"r")}${Tt("62%")}</div>
276
+ <div class="sk-bullet">${Tt("6px",6,"r")}${Tt("48%")}</div>
277
+ <div class="sk-bullet">${Tt("6px",6,"r")}${Tt("55%")}</div>
278
+ <div class="sk-gap"></div>${Tt("28%",22)}
279
+ <div class="sk-table">${[0,1,2,3].map(()=>`<div>${Tt("70%")}${Tt("55%")}${Tt("62%")}${Tt("80%")}</div>`).join("")}</div>
280
280
  ${_l([94,88,72])}
281
281
  </div>
282
- </div></div></div>`}function yA(){return at("skeleton-css",Td),`<div aria-busy="true" aria-label="Loading the preview">${At("45%",16)}${_l([96,90,64])}<div class="sk-gap" style="height:10px"></div>${At("35%",14)}${_l([92,70])}</div>`}function Xo(n=6,e=!0){return at("skeleton-css",Td),Array.from({length:n},(t,i)=>`<div class="sk-li" aria-hidden="true">${At("32px",32,e?"r":"")}<div class="sk-stack">${At(`${50+i*13%30}%`,11)}<span style="height:7px"></span>${At(`${30+i*17%35}%`,9)}</div>${At("44px",10)}</div>`).join("")}function Lt(n,e=12,t=""){return at("skeleton-css",Td),At(n,e,t)}const ye={path:null,base:"",doc:null,timer:0,status:"saved",lastSavedAt:0,theirs:null,theirsBy:""};let Ft=null,Ed=null,Qs=!1,bf=0;function yf(){const n=Ft?.querySelector(".vx-editor");return!!(D.editing&&n&&n.value!==ye.base)}window.addEventListener("beforeunload",n=>{yf()&&(n.preventDefault(),n.returnValue="")});async function Sl(){yf()&&ye.status!=="conflict"&&await Rd()}function wA(){return ye.path}async function Ko(n,e,t,i=!1){Ft=n,Qs=t,zA(),i||(n.innerHTML=bA());const a=++bf;let s;try{s=await nt("/api/note?path="+encodeURIComponent(e))}catch(o){if(a!==bf||D.note!==e||Ks(e)||Ks())return;n.innerHTML=`<div class="vx-empty">${xe.warn}<p>Could not open <b>${b(e)}</b><br>${b(o.message)}</p></div>`,ye.path=null;return}a!==bf||D.note!==e||(ye.path!==(s.path||e)&&(ye.lastSavedAt=0),ye.path=s.path||e,ye.base=s.content||"",ye.doc=s,ye.status="saved",ye.theirs=null,ts(),Ks()||n.classList.remove("vx-busy"))}function ts(){const n=Ft,e=ye.doc;if(!n||!e)return;mi(),Yo();const t=ye.path||e.path,i=De(t),a=i?i.split("/").map((R,B,K)=>K.slice(0,B+1).join("/")):[],s=e.tags&&e.tags.length?e.tags:[],o=e.backlinks||[],r=Array.from(new Set($S(e.content))),l=(e.content||"").replace(/^---[\s\S]*?---/,"").split(/\s+/).filter(Boolean).length,c=Si.get(t),p=_i("note",t),h=n.querySelector(".vx-note-scroll")?.scrollTop||0;n.style.setProperty("--fc",kn(i)),n.innerHTML="";const d=`<button class="vx-crumb" data-f="">${xe.vault}<span>Vault</span></button>${a.map(R=>`<span class="vx-crumb-sep" aria-hidden="true">/</span><button class="vx-crumb" data-f="${O(R)}"><span>${b(Dt(R))}</span></button>`).join("")}<span class="vx-crumb-sep" aria-hidden="true">/</span><span class="vx-crumb cur" aria-current="page"><span>${b(bt(t))}</span></span>`,u=we("header","vx-rbar");u.innerHTML=`<button class="vx-icon-btn vx-back" data-back aria-label="Back" title="Back">${xe.back}</button>
282
+ </div></div></div>`}function yA(){return at("skeleton-css",Td),`<div aria-busy="true" aria-label="Loading the preview">${Tt("45%",16)}${_l([96,90,64])}<div class="sk-gap" style="height:10px"></div>${Tt("35%",14)}${_l([92,70])}</div>`}function Xo(n=6,e=!0){return at("skeleton-css",Td),Array.from({length:n},(t,i)=>`<div class="sk-li" aria-hidden="true">${Tt("32px",32,e?"r":"")}<div class="sk-stack">${Tt(`${50+i*13%30}%`,11)}<span style="height:7px"></span>${Tt(`${30+i*17%35}%`,9)}</div>${Tt("44px",10)}</div>`).join("")}function Lt(n,e=12,t=""){return at("skeleton-css",Td),Tt(n,e,t)}const ye={path:null,base:"",doc:null,timer:0,status:"saved",lastSavedAt:0,theirs:null,theirsBy:""};let Ft=null,Ed=null,Qs=!1,bf=0;function yf(){const n=Ft?.querySelector(".vx-editor");return!!(D.editing&&n&&n.value!==ye.base)}window.addEventListener("beforeunload",n=>{yf()&&(n.preventDefault(),n.returnValue="")});async function Sl(){yf()&&ye.status!=="conflict"&&await Rd()}function wA(){return ye.path}async function Ko(n,e,t,i=!1){Ft=n,Qs=t,zA(),i||(n.innerHTML=bA());const a=++bf;let s;try{s=await nt("/api/note?path="+encodeURIComponent(e))}catch(o){if(a!==bf||D.note!==e||Ks(e)||Ks())return;n.innerHTML=`<div class="vx-empty">${xe.warn}<p>Could not open <b>${b(e)}</b><br>${b(o.message)}</p></div>`,ye.path=null;return}a!==bf||D.note!==e||(ye.path!==(s.path||e)&&(ye.lastSavedAt=0),ye.path=s.path||e,ye.base=s.content||"",ye.doc=s,ye.status="saved",ye.theirs=null,ts(),Ks()||n.classList.remove("vx-busy"))}function ts(){const n=Ft,e=ye.doc;if(!n||!e)return;mi(),Yo();const t=ye.path||e.path,i=De(t),a=i?i.split("/").map((R,B,K)=>K.slice(0,B+1).join("/")):[],s=e.tags&&e.tags.length?e.tags:[],o=e.backlinks||[],r=Array.from(new Set($S(e.content))),l=(e.content||"").replace(/^---[\s\S]*?---/,"").split(/\s+/).filter(Boolean).length,c=Si.get(t),p=_i("note",t),h=n.querySelector(".vx-note-scroll")?.scrollTop||0;n.style.setProperty("--fc",kn(i)),n.innerHTML="";const d=`<button class="vx-crumb" data-f="">${xe.vault}<span>Vault</span></button>${a.map(R=>`<span class="vx-crumb-sep" aria-hidden="true">/</span><button class="vx-crumb" data-f="${O(R)}"><span>${b(Dt(R))}</span></button>`).join("")}<span class="vx-crumb-sep" aria-hidden="true">/</span><span class="vx-crumb cur" aria-current="page"><span>${b(bt(t))}</span></span>`,u=we("header","vx-rbar");u.innerHTML=`<button class="vx-icon-btn vx-back" data-back aria-label="Back" title="Back">${xe.back}</button>
283
283
  <nav class="vx-crumbs" aria-label="Breadcrumb">${d}</nav>
284
284
  <span class="vx-grow"></span>
285
285
  <span class="vx-save" data-state="${ye.status}" aria-live="polite"></span>
@@ -2382,7 +2382,7 @@ export MEMORA_KEY=${t}`,rules:"<code>AGENTS.md</code> in the project, or <code>~
2382
2382
  <div class="cn-copy"><span>${H==="short"?"A few lines, for small context windows":"The complete guide, best for most agents"}</span>
2383
2383
  <button type="button" class="btn primary" data-copy="${O(Y)}">${de.copy}Copy ${H==="short"?"short":"full"} instructions</button></div></div>
2384
2384
  <a class="cn-doc" href="/docs/agent-instructions" id="cnDoc">Read the full documentation ${de.arrow}</a>
2385
- <div class="cn-test" style="margin-top:18px"><div class="cn-live" data-live role="status" aria-live="polite"></div></div>`},Be=()=>{const $=_().indexOf(l)<=0,H=l==="prompt"?"Done":l==="access"&&!i?"Create key":"Continue";e.setNav({back:!$,next:H})},ct=($=!1)=>{if(g)return;const H=l==="app"?V():l==="access"?Z():l==="setup"?ce():Ne();n.innerHTML=`<div class="cn-wz">${R()}<div class="cn-step">${H}</div></div>`,u=null,as(n),Ce(),Be(),z(),L(),e.setSub?.(x()?.label||(t?i.name:"Pick an app")),e.onInfo?.(ot()),$&&(n.getBoundingClientRect().top<0&&n.scrollIntoView({block:"start"}),n.querySelector(".cn-h")?.focus({preventScroll:!0}))},ot=()=>{const $=n.querySelector("#cnName"),H=$?$.value.trim():p?c:S();let Y="";if(i?.perms)Y=wm(i.perms);else if(!i&&x()&&!x().oauth){const j=h==="custom"?u?u.read():d:Ql(h,Jl());Y=j?wm(j):h==="custom"?"Custom":""}else x()?.oauth&&!i&&(Y="Chosen when it signs in");return{step:l,client:x()||null,agent:i,name:i?i.name:H,access:Y,connectedId:M,connected:!!y}},ft=()=>{if(l!=="access"||i)return;const $=n.querySelector("#cnName");$&&p&&(c=$.value),u&&(d=u.read())},ne=$=>{if(!w($)){x()||He("Pick an app first","warn");return}ft(),l=$,ct(!0)},oe=$=>{if(o=$,i){e.onAppChosen?.(i.id,$),ne("setup");return}ne(x()?.oauth?"setup":"access")},Te=()=>{const $=n.querySelector("#cnCustom");if(!$||($.hidden=h!=="custom",h!=="custom"||u))return;const H=Jl(),Y=d||Ql("rw",H);$.innerHTML=u1(Y,H),u=f1($,Y,H)},We=async()=>{if(i)return ne("setup");const $=n.querySelector("#cnName"),H=$.value.trim();if(!H){He("Give the agent a name","warn"),$.focus();return}let Y;if(h==="custom"){const pe=u?.problem();if(pe){He(pe,"warn");return}Y=u?u.read():d}else Y=Ql(h,Jl());Y||(Y=Ql("rw",null));const j=await e.createAgent(H,Y);!j||g||(i={...j.key,perms:Y},a.set(i.id,j.secret),s.add(i.id),e.onAppChosen?.(i.id,o),l="setup",ct(!0))},Ce=()=>{n.querySelectorAll("[data-go]").forEach(Ue=>Ue.onclick=()=>ne(Ue.dataset.go)),n.querySelectorAll("[data-client]").forEach(Ue=>Ue.onclick=()=>oe(Ue.dataset.client));const $=n.querySelector("#cnQ");$&&($.oninput=()=>{const Ue=$.value.trim().toLowerCase();let je=0;n.querySelectorAll("[data-group]").forEach(F=>{let lt=0;F.querySelectorAll("[data-client]").forEach(Ze=>{Ze.hidden=!!Ue&&!Ze.dataset.q.includes(Ue),Ze.hidden||lt++}),F.hidden=!lt,je+=lt}),n.querySelector("#cnNone").hidden=je>0},$.onkeydown=Ue=>{if(Ue.key!=="Enter")return;Ue.preventDefault();const je=Array.from(n.querySelectorAll("[data-client]")).filter(F=>!F.hidden);je.length===1&&oe(je[0].dataset.client)});const H=n.querySelector("#cnName");H&&(H.oninput=()=>p=!0,H.onkeydown=Ue=>{Ue.key==="Enter"&&(Ue.preventDefault(),We())});const Y=n.querySelector(".cn-acc");Y&&(d1(Y,Ue=>{h=Ue,Te()}),Te());const j=n.querySelector("#cnKeyEye");j&&(j.onclick=()=>{f=!f,ct(),n.querySelector("#cnKeyEye")?.focus()});const pe=n.querySelector("#cnKeyCopy");pe&&(pe.onclick=()=>{ka(m(),"Key copied")});const fe=i,Ve=n.querySelector("#cnUnlock");Ve&&fe&&(Ve.onsubmit=async Ue=>{Ue.preventDefault();const je=n.querySelector("#cnPw");if(!je.value){He("Enter your Memora password","warn"),je.focus();return}const F=Ve.querySelector("button[type=submit]");F.disabled=!0;try{const lt=await ht("/api/keys/reveal",{id:fe.id,current:je.value});if(!lt||!lt.key)throw new Error("the server returned no key");a.set(fe.id,lt.key),He("Key unlocked and filled in","ok"),ct(),n.querySelector("#cnKeyCopy")?.focus()}catch(lt){F.disabled=!1,He(lt.message||"Could not unlock the key","err"),je.select()}}),n.querySelectorAll("[data-roll]").forEach(Ue=>{fe&&(Ue.onclick=()=>Ie.confirm("Make a new key",`${fe.name}'s current key stops working at once. The new one is filled in here; update the app that uses the old one.`,"Make a new key",async()=>{try{const je=await ht("/api/keys/roll",{id:fe.id});Ie.close(),je&&je.key&&(a.set(fe.id,je.key),s.add(fe.id),f=!1,e.onChange?.(),He("New key made and filled in","ok"),ct())}catch(je){He("Could not make a new key: "+je.message,"err")}},!1))});const st=Array.from(n.querySelectorAll("[data-pk]"));st.forEach(Ue=>{Ue.onclick=()=>{v=Ue.dataset.pk,ct(),n.querySelector(`[data-pk="${v}"]`)?.focus()},Ue.onkeydown=je=>{je.key!=="ArrowRight"&&je.key!=="ArrowLeft"||(je.preventDefault(),st.find(F=>F!==Ue)?.click())}});const kt=n.querySelector("#cnDoc");kt&&kt.addEventListener("click",()=>cT())};return ct(),{info:ot,back:()=>{const $=_(),H=$.indexOf(l);H>0&&ne($[H-1])},next:async()=>l==="prompt"?!0:l==="app"?(x()?oe(o):He("Pick an app first","warn"),!1):l==="access"?(await We(),!1):(ne("prompt"),!1),destroy:()=>{g=!0,C()}}}const b1="/api/ui/layout/agent-apps";let ls={},gp=null;function e3(n=!1){return gp&&!n||(gp=nt(b1).then(e=>{const t=e?.data?.apps;if(ls={},t&&typeof t=="object")for(const[i,a]of Object.entries(t))typeof a=="string"&&(ls[i]=a)}).catch(()=>{ls={}})),gp}async function Sm(n,e){if(!(!n||(ls[n]||"")===e)){e?ls[n]=e:delete ls[n];try{await Nn(b1,{method:"PUT",body:{data:{apps:ls}}})}catch{}}}const t3=[[/claude[\s._-]*code|^cc$/,"claude-code"],[/claude[\s._-]*desktop/,"claude-desktop"],[/cursor/,"cursor"],[/vs[\s._-]*code|copilot/,"vscode"],[/codex/,"codex"],[/gemini/,"gemini"],[/windsurf|codeium|cascade/,"windsurf"],[/chat[\s._-]*gpt|openai/,"chatgpt"],[/claude|anthropic/,"claude-ai"]];function n3(...n){for(const e of n){const t=String(e||"").toLowerCase();if(t){for(const[i,a]of t3)if(i.test(t))return a}}return""}function i3(n,e){const t=ls[n.id];return t?{id:t,guessed:!1}:{id:n3(e,n.name),guessed:!0}}const cs={create:"/api/keys",roll:"/api/keys/roll",update:"/api/keys/update",del:"/api/keys/delete",restore:"/api/keys/restore",reveal:"/api/keys/reveal"},a3=300,Tt={keys:[],oauth:new Map,usage:new Map,loaded:!1,error:""},vp=new Map,$t=n=>n.name||n.id,xp=n=>({scopes:HE(n),tools:GE(n)}),y1=n=>Tt.keys.find(e=>e.id===n);function lo(n){return Tt.usage.get("id:"+n.id)||Tt.usage.get(va($t(n)))}function ds(n){const e=i3(n,Tt.oauth.get(n.id)),t=e.id?Xi(e.id):void 0;return{id:t?e.id:"",label:t?.label||"",guessed:e.guessed}}function co(n,e=Date.now()/1e3){const t=lo(n),i=t?Un(t.last)==="now"?"Just now":Un(t.last)+" ago":n.uses?"Over a week ago":"Never";return n.enabled===!1?{st:"off",label:"Off",seen:i}:t&&e-t.last<a3?{st:"active",label:"Active",seen:i}:t||n.uses?{st:"idle",label:"Idle",seen:i}:{st:"never",label:"Never used",seen:i}}function s3(n){return{id:n.id,name:$t(n),revealable:n.revealable,oauth:Tt.oauth.has(n.id),perms:xp(n)}}const Mm=new Set;function w1(n){return Mm.add(n),()=>Mm.delete(n)}function o3(){for(const n of[...Mm])try{n()}catch(e){console.error("agents repaint failed",e)}}let Am=0,ec=null;function Fn(n=!1){if(ec&&!n)return ec;const e=++Am,t=(async()=>{const i=ym(n||!Jl()),a=e3(n),s=Id("7d",1500).catch(()=>[]);try{const o=await nt("/api/keys"),r=Array.isArray(o)?o:o.keys||[],l=await nt("/api/oauth/clients").catch(()=>null);await Promise.all([i,a]);const c=await s;if(e!==Am)return;Tt.keys=r,Gu(r);const p=new Map((l?.clients||[]).map(u=>[u.client_id,u.name||u.client_name||""]));Tt.oauth=new Map((l?.connections||[]).map(u=>[u.key_id,p.get(u.client_id)||""]));const h=Date.now()/1e3,d=new Map;for(const u of c){if(u.source!=="agent")continue;const f=typeof u.raw.actor_id=="string"&&u.raw.actor_id?"id:"+u.raw.actor_id:va(u.actor);let v=d.get(f);v||d.set(f,v={last:u.ts,day:0,spark:new Array(24).fill(0)}),u.ts>v.last&&(v.last=u.ts);const g=Math.floor((h-u.ts)/3600);g>=0&&g<24&&(v.day++,v.spark[23-g]++)}Tt.usage=d,Tt.loaded=!0,Tt.error=""}catch(o){if(e!==Am)return;Tt.error=o.message||"Could not load the agents"}o3()})();return ec=t,t.finally(()=>{ec===t&&(ec=null)}),t}function k1(n){let e=!1;for(const t of n){if(t.kind!=="agent")continue;const i=Tt.keys.find(r=>t.id?r.id===t.id:va($t(r))===va(t.actor));if(!i)continue;const a=Tt.usage.has("id:"+i.id)||t.id?"id:"+i.id:va($t(i)),s=Math.floor(t.lastAt/1e3),o=Tt.usage.get(a);if(!o)Tt.usage.set(a,{last:s,day:0,spark:new Array(24).fill(0)});else if(s>o.last)o.last=s;else continue;e=!0}return e}function Ki(n="",e=!1){Zu(n?"/agents/"+n:null),e&&ba(),jn("keys")}function pr(n=""){return"/agents"+(n?"/"+n.split("/").map(encodeURIComponent).join("/"):"")}function ps(n){n.querySelectorAll("a[data-nav]").forEach(e=>{e.onclick=t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||t.button!==0||(t.preventDefault(),Ki(e.dataset.nav||""))}})}function Tm(n){history.pushState(null,"","/activity/"+encodeURIComponent(n.id)),window.dispatchEvent(new PopStateEvent("popstate"))}async function _1(n,e){try{const t=await ht(cs.create,{name:n,scopes:e.scopes,tools:e.tools});if(!t||!t.id||!t.key)throw new Error("the server returned no key");if(Array.isArray(e.tools))try{await db({id:t.id,scopes:e.scopes,tools:e.tools})}catch(i){He("Agent created, but its tool list was not saved: "+i.message,"err",6e3)}return vp.set(t.id,t.key),Fn(!0),{key:{id:t.id,name:t.name||n,perms:e},secret:t.key}}catch(t){return He("Could not create the agent: "+t.message,"err"),null}}async function bp(n){const e=n.enabled!==!1;try{await ht(cs.update,{id:n.id,enabled:!e}),He(e?`${$t(n)} is turned off`:`${$t(n)} is turned on`,"ok"),await Fn(!0)}catch(t){He("Failed: "+t.message,"err")}}function S1(n,e){const t=$t(n);Ie.confirm("Make a new key",`${t}'s current key stops working at once. The new key is shown next; update the app that uses ${t}.`,"Make a new key",async()=>{try{const i=await ht(cs.roll,{id:n.id});Ie.close();const a=i&&(i.key||i.secret)||"";a&&vp.set(n.id,a),r3(n,a,e),Fn(!0)}catch(i){He("Could not make a new key: "+i.message,"err")}},!1)}function r3(n,e,t){const i=$t(n),a=!!e;Ud({title:"New key made",sub:i,lead:qt(i,36,"",n.id),width:560,body:`<div class="ky-secret" role="note">${de.key}<span><b>This key is shown once. Copy it now and keep it private.</b> Anyone with this key can read and write your notes as ${b(i)}. The old key stopped working.</span></div>
2385
+ <div class="cn-test" style="margin-top:18px"><div class="cn-live" data-live role="status" aria-live="polite"></div></div>`},Be=()=>{const $=_().indexOf(l)<=0,H=l==="prompt"?"Done":l==="access"&&!i?"Create key":"Continue";e.setNav({back:!$,next:H})},ct=($=!1)=>{if(g)return;const H=l==="app"?V():l==="access"?Z():l==="setup"?ce():Ne();n.innerHTML=`<div class="cn-wz">${R()}<div class="cn-step">${H}</div></div>`,u=null,as(n),Ce(),Be(),z(),L(),e.setSub?.(x()?.label||(t?i.name:"Pick an app")),e.onInfo?.(ot()),$&&(n.getBoundingClientRect().top<0&&n.scrollIntoView({block:"start"}),n.querySelector(".cn-h")?.focus({preventScroll:!0}))},ot=()=>{const $=n.querySelector("#cnName"),H=$?$.value.trim():p?c:S();let Y="";if(i?.perms)Y=wm(i.perms);else if(!i&&x()&&!x().oauth){const j=h==="custom"?u?u.read():d:Ql(h,Jl());Y=j?wm(j):h==="custom"?"Custom":""}else x()?.oauth&&!i&&(Y="Chosen when it signs in");return{step:l,client:x()||null,agent:i,name:i?i.name:H,access:Y,connectedId:M,connected:!!y}},ft=()=>{if(l!=="access"||i)return;const $=n.querySelector("#cnName");$&&p&&(c=$.value),u&&(d=u.read())},ne=$=>{if(!w($)){x()||He("Pick an app first","warn");return}ft(),l=$,ct(!0)},oe=$=>{if(o=$,i){e.onAppChosen?.(i.id,$),ne("setup");return}ne(x()?.oauth?"setup":"access")},Te=()=>{const $=n.querySelector("#cnCustom");if(!$||($.hidden=h!=="custom",h!=="custom"||u))return;const H=Jl(),Y=d||Ql("rw",H);$.innerHTML=u1(Y,H),u=f1($,Y,H)},We=async()=>{if(i)return ne("setup");const $=n.querySelector("#cnName"),H=$.value.trim();if(!H){He("Give the agent a name","warn"),$.focus();return}let Y;if(h==="custom"){const pe=u?.problem();if(pe){He(pe,"warn");return}Y=u?u.read():d}else Y=Ql(h,Jl());Y||(Y=Ql("rw",null));const j=await e.createAgent(H,Y);!j||g||(i={...j.key,perms:Y},a.set(i.id,j.secret),s.add(i.id),e.onAppChosen?.(i.id,o),l="setup",ct(!0))},Ce=()=>{n.querySelectorAll("[data-go]").forEach(Ue=>Ue.onclick=()=>ne(Ue.dataset.go)),n.querySelectorAll("[data-client]").forEach(Ue=>Ue.onclick=()=>oe(Ue.dataset.client));const $=n.querySelector("#cnQ");$&&($.oninput=()=>{const Ue=$.value.trim().toLowerCase();let je=0;n.querySelectorAll("[data-group]").forEach(F=>{let lt=0;F.querySelectorAll("[data-client]").forEach(Ze=>{Ze.hidden=!!Ue&&!Ze.dataset.q.includes(Ue),Ze.hidden||lt++}),F.hidden=!lt,je+=lt}),n.querySelector("#cnNone").hidden=je>0},$.onkeydown=Ue=>{if(Ue.key!=="Enter")return;Ue.preventDefault();const je=Array.from(n.querySelectorAll("[data-client]")).filter(F=>!F.hidden);je.length===1&&oe(je[0].dataset.client)});const H=n.querySelector("#cnName");H&&(H.oninput=()=>p=!0,H.onkeydown=Ue=>{Ue.key==="Enter"&&(Ue.preventDefault(),We())});const Y=n.querySelector(".cn-acc");Y&&(d1(Y,Ue=>{h=Ue,Te()}),Te());const j=n.querySelector("#cnKeyEye");j&&(j.onclick=()=>{f=!f,ct(),n.querySelector("#cnKeyEye")?.focus()});const pe=n.querySelector("#cnKeyCopy");pe&&(pe.onclick=()=>{ka(m(),"Key copied")});const fe=i,Ve=n.querySelector("#cnUnlock");Ve&&fe&&(Ve.onsubmit=async Ue=>{Ue.preventDefault();const je=n.querySelector("#cnPw");if(!je.value){He("Enter your Memora password","warn"),je.focus();return}const F=Ve.querySelector("button[type=submit]");F.disabled=!0;try{const lt=await ht("/api/keys/reveal",{id:fe.id,current:je.value});if(!lt||!lt.key)throw new Error("the server returned no key");a.set(fe.id,lt.key),He("Key unlocked and filled in","ok"),ct(),n.querySelector("#cnKeyCopy")?.focus()}catch(lt){F.disabled=!1,He(lt.message||"Could not unlock the key","err"),je.select()}}),n.querySelectorAll("[data-roll]").forEach(Ue=>{fe&&(Ue.onclick=()=>Ie.confirm("Make a new key",`${fe.name}'s current key stops working at once. The new one is filled in here; update the app that uses the old one.`,"Make a new key",async()=>{try{const je=await ht("/api/keys/roll",{id:fe.id});Ie.close(),je&&je.key&&(a.set(fe.id,je.key),s.add(fe.id),f=!1,e.onChange?.(),He("New key made and filled in","ok"),ct())}catch(je){He("Could not make a new key: "+je.message,"err")}},!1))});const st=Array.from(n.querySelectorAll("[data-pk]"));st.forEach(Ue=>{Ue.onclick=()=>{v=Ue.dataset.pk,ct(),n.querySelector(`[data-pk="${v}"]`)?.focus()},Ue.onkeydown=je=>{je.key!=="ArrowRight"&&je.key!=="ArrowLeft"||(je.preventDefault(),st.find(F=>F!==Ue)?.click())}});const kt=n.querySelector("#cnDoc");kt&&kt.addEventListener("click",()=>cT())};return ct(),{info:ot,back:()=>{const $=_(),H=$.indexOf(l);H>0&&ne($[H-1])},next:async()=>l==="prompt"?!0:l==="app"?(x()?oe(o):He("Pick an app first","warn"),!1):l==="access"?(await We(),!1):(ne("prompt"),!1),destroy:()=>{g=!0,C()}}}const b1="/api/ui/layout/agent-apps";let ls={},gp=null;function e3(n=!1){return gp&&!n||(gp=nt(b1).then(e=>{const t=e?.data?.apps;if(ls={},t&&typeof t=="object")for(const[i,a]of Object.entries(t))typeof a=="string"&&(ls[i]=a)}).catch(()=>{ls={}})),gp}async function Sm(n,e){if(!(!n||(ls[n]||"")===e)){e?ls[n]=e:delete ls[n];try{await Nn(b1,{method:"PUT",body:{data:{apps:ls}}})}catch{}}}const t3=[[/claude[\s._-]*code|^cc$/,"claude-code"],[/claude[\s._-]*desktop/,"claude-desktop"],[/cursor/,"cursor"],[/vs[\s._-]*code|copilot/,"vscode"],[/codex/,"codex"],[/gemini/,"gemini"],[/windsurf|codeium|cascade/,"windsurf"],[/chat[\s._-]*gpt|openai/,"chatgpt"],[/claude|anthropic/,"claude-ai"]];function n3(...n){for(const e of n){const t=String(e||"").toLowerCase();if(t){for(const[i,a]of t3)if(i.test(t))return a}}return""}function i3(n,e){const t=ls[n.id];return t?{id:t,guessed:!1}:{id:n3(e,n.name),guessed:!0}}const cs={create:"/api/keys",roll:"/api/keys/roll",update:"/api/keys/update",del:"/api/keys/delete",restore:"/api/keys/restore",reveal:"/api/keys/reveal"},a3=300,Et={keys:[],oauth:new Map,usage:new Map,loaded:!1,error:""},vp=new Map,$t=n=>n.name||n.id,xp=n=>({scopes:HE(n),tools:GE(n)}),y1=n=>Et.keys.find(e=>e.id===n);function lo(n){return Et.usage.get("id:"+n.id)||Et.usage.get(va($t(n)))}function ds(n){const e=i3(n,Et.oauth.get(n.id)),t=e.id?Xi(e.id):void 0;return{id:t?e.id:"",label:t?.label||"",guessed:e.guessed}}function co(n,e=Date.now()/1e3){const t=lo(n),i=t?Un(t.last)==="now"?"Just now":Un(t.last)+" ago":n.uses?"Over a week ago":"Never";return n.enabled===!1?{st:"off",label:"Off",seen:i}:t&&e-t.last<a3?{st:"active",label:"Active",seen:i}:t||n.uses?{st:"idle",label:"Idle",seen:i}:{st:"never",label:"Never used",seen:i}}function s3(n){return{id:n.id,name:$t(n),revealable:n.revealable,oauth:Et.oauth.has(n.id),perms:xp(n)}}const Mm=new Set;function w1(n){return Mm.add(n),()=>Mm.delete(n)}function o3(){for(const n of[...Mm])try{n()}catch(e){console.error("agents repaint failed",e)}}let Am=0,ec=null;function Fn(n=!1){if(ec&&!n)return ec;const e=++Am,t=(async()=>{const i=ym(n||!Jl()),a=e3(n),s=Id("7d",1500).catch(()=>[]);try{const o=await nt("/api/keys"),r=Array.isArray(o)?o:o.keys||[],l=await nt("/api/oauth/clients").catch(()=>null);await Promise.all([i,a]);const c=await s;if(e!==Am)return;Et.keys=r,Gu(r);const p=new Map((l?.clients||[]).map(u=>[u.client_id,u.name||u.client_name||""]));Et.oauth=new Map((l?.connections||[]).map(u=>[u.key_id,p.get(u.client_id)||""]));const h=Date.now()/1e3,d=new Map;for(const u of c){if(u.source!=="agent")continue;const f=typeof u.raw.actor_id=="string"&&u.raw.actor_id?"id:"+u.raw.actor_id:va(u.actor);let v=d.get(f);v||d.set(f,v={last:u.ts,day:0,spark:new Array(24).fill(0)}),u.ts>v.last&&(v.last=u.ts);const g=Math.floor((h-u.ts)/3600);g>=0&&g<24&&(v.day++,v.spark[23-g]++)}Et.usage=d,Et.loaded=!0,Et.error=""}catch(o){if(e!==Am)return;Et.error=o.message||"Could not load the agents"}o3()})();return ec=t,t.finally(()=>{ec===t&&(ec=null)}),t}function k1(n){let e=!1;for(const t of n){if(t.kind!=="agent")continue;const i=Et.keys.find(r=>t.id?r.id===t.id:va($t(r))===va(t.actor));if(!i)continue;const a=Et.usage.has("id:"+i.id)||t.id?"id:"+i.id:va($t(i)),s=Math.floor(t.lastAt/1e3),o=Et.usage.get(a);if(!o)Et.usage.set(a,{last:s,day:0,spark:new Array(24).fill(0)});else if(s>o.last)o.last=s;else continue;e=!0}return e}function Ki(n="",e=!1){Zu(n?"/agents/"+n:null),e&&ba(),jn("keys")}function pr(n=""){return"/agents"+(n?"/"+n.split("/").map(encodeURIComponent).join("/"):"")}function ps(n){n.querySelectorAll("a[data-nav]").forEach(e=>{e.onclick=t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||t.button!==0||(t.preventDefault(),Ki(e.dataset.nav||""))}})}function Tm(n){history.pushState(null,"","/activity/"+encodeURIComponent(n.id)),window.dispatchEvent(new PopStateEvent("popstate"))}async function _1(n,e){try{const t=await ht(cs.create,{name:n,scopes:e.scopes,tools:e.tools});if(!t||!t.id||!t.key)throw new Error("the server returned no key");if(Array.isArray(e.tools))try{await db({id:t.id,scopes:e.scopes,tools:e.tools})}catch(i){He("Agent created, but its tool list was not saved: "+i.message,"err",6e3)}return vp.set(t.id,t.key),Fn(!0),{key:{id:t.id,name:t.name||n,perms:e},secret:t.key}}catch(t){return He("Could not create the agent: "+t.message,"err"),null}}async function bp(n){const e=n.enabled!==!1;try{await ht(cs.update,{id:n.id,enabled:!e}),He(e?`${$t(n)} is turned off`:`${$t(n)} is turned on`,"ok"),await Fn(!0)}catch(t){He("Failed: "+t.message,"err")}}function S1(n,e){const t=$t(n);Ie.confirm("Make a new key",`${t}'s current key stops working at once. The new key is shown next; update the app that uses ${t}.`,"Make a new key",async()=>{try{const i=await ht(cs.roll,{id:n.id});Ie.close();const a=i&&(i.key||i.secret)||"";a&&vp.set(n.id,a),r3(n,a,e),Fn(!0)}catch(i){He("Could not make a new key: "+i.message,"err")}},!1)}function r3(n,e,t){const i=$t(n),a=!!e;Ud({title:"New key made",sub:i,lead:qt(i,36,"",n.id),width:560,body:`<div class="ky-secret" role="note">${de.key}<span><b>This key is shown once. Copy it now and keep it private.</b> Anyone with this key can read and write your notes as ${b(i)}. The old key stopped working.</span></div>
2386
2386
  ${Dd(a?e:"The server did not return a key.","Copy key")}`,actions:[{label:"Copy key",icon:de.copy,left:!0,run:()=>{ka(a?e:"","Key copied")}},...a&&t?[{label:"Set up with the new key",cls:"primary",icon:de.plug,run:s=>(s.close(),t())}]:[{label:"Done",cls:"primary",run:s=>s.close()}]]})}function M1(n){const e=$t(n);Ud({title:"Show key",sub:e,lead:qt(e,36,"",n.id),width:520,body:`<form id="krForm" class="ui-fld" style="margin:0"><label for="krPw">Your Memora password</label>
2387
2387
  <input id="krPw" class="ui-input" type="password" autocomplete="current-password">
2388
2388
  <span class="ui-help">The key is stored sealed on the server; your password unlocks it.</span></form>
@@ -2864,7 +2864,7 @@ export MEMORA_KEY=${t}`,rules:"<code>AGENTS.md</code> in the project, or <code>~
2864
2864
  }
2865
2865
  @media (max-width:760px){.ap{--ap-pt:16px;--ap-pb:32px}}
2866
2866
  @media (prefers-reduced-motion:reduce){.ap-ev.new{animation:none}.ap-ev-st.run i{animation:none}}
2867
- `,oC={read:kp,search:de.search,write:T1,delete:yp,auth:de.key,other:Cm},Qt={status:"all",range:"7d",q:"",limit:80};let ge=null;function sw(){at("agent-page-css",sC)}async function rC(n,e,t){sw();const i=ju.includes(t)?t:"overview";if(ge&&ge.id===e&&ge.root.isConnected&&n.contains(ge.root)){ge.tab!==i&&fC(i);return}ge?.wizard?.destroy(),Qt.status="all",Qt.range="7d",Qt.q="",Qt.limit=80,n.innerHTML=`<div class="cc ap" data-id="${O(e)}"></div>`;const a=n.firstElementChild;ge={id:e,tab:i,root:a,events:null,range:"",evSeq:0,fresh:new Set,wizard:null,perms:null,picking:!1};const s=ge;if(Ll(n,()=>{let o=0;const r=Nl((d,u)=>{k1(u)&&!o&&(o=window.setTimeout(()=>(o=0,ge===s&&mr()),600))}),l=Pf(d=>ge===s&&gC(d)),c=w1(()=>ge===s&&cC()),p=window.setInterval(()=>ge===s&&mr(),3e4),h=()=>{const d=s.root.querySelector(".ap-tabs");d&&d.classList.toggle("stuck",n.scrollTop>0&&d.getBoundingClientRect().top<=n.getBoundingClientRect().top+1)};return n.addEventListener("scroll",h,{passive:!0}),()=>{n.removeEventListener("scroll",h),r(),l(),c(),clearTimeout(o),clearInterval(p),s.wizard?.destroy(),s.wizard=null,ge===s&&(ge=null)}}),Tt.loaded&&y1(e))Pp(!0),Fn(!0);else{if(a.innerHTML=lC(),await Fn(!0),ge!==s)return;Pp(!0)}}const di=()=>ge?y1(ge.id):void 0;function lC(){return`<div class="ap-crumb">${Lt("80px",20)}</div><div class="ap-head" aria-busy="true">${Lt("56px",56,"r")}
2867
+ `,oC={read:kp,search:de.search,write:T1,delete:yp,auth:de.key,other:Cm},Qt={status:"all",range:"7d",q:"",limit:80};let ge=null;function sw(){at("agent-page-css",sC)}async function rC(n,e,t){sw();const i=ju.includes(t)?t:"overview";if(ge&&ge.id===e&&ge.root.isConnected&&n.contains(ge.root)){ge.tab!==i&&fC(i);return}ge?.wizard?.destroy(),Qt.status="all",Qt.range="7d",Qt.q="",Qt.limit=80,n.innerHTML=`<div class="cc ap" data-id="${O(e)}"></div>`;const a=n.firstElementChild;ge={id:e,tab:i,root:a,events:null,range:"",evSeq:0,fresh:new Set,wizard:null,perms:null,picking:!1};const s=ge;if(Ll(n,()=>{let o=0;const r=Nl((d,u)=>{k1(u)&&!o&&(o=window.setTimeout(()=>(o=0,ge===s&&mr()),600))}),l=Pf(d=>ge===s&&gC(d)),c=w1(()=>ge===s&&cC()),p=window.setInterval(()=>ge===s&&mr(),3e4),h=()=>{const d=s.root.querySelector(".ap-tabs");d&&d.classList.toggle("stuck",n.scrollTop>0&&d.getBoundingClientRect().top<=n.getBoundingClientRect().top+1)};return n.addEventListener("scroll",h,{passive:!0}),()=>{n.removeEventListener("scroll",h),r(),l(),c(),clearTimeout(o),clearInterval(p),s.wizard?.destroy(),s.wizard=null,ge===s&&(ge=null)}}),Et.loaded&&y1(e))Pp(!0),Fn(!0);else{if(a.innerHTML=lC(),await Fn(!0),ge!==s)return;Pp(!0)}}const di=()=>ge?y1(ge.id):void 0;function lC(){return`<div class="ap-crumb">${Lt("80px",20)}</div><div class="ap-head" aria-busy="true">${Lt("56px",56,"r")}
2868
2868
  <div class="ap-id">${Lt("min(260px,60%)",24)}${Lt("min(340px,80%)",14)}</div></div>
2869
2869
  <div class="ap-card" style="margin-top:20px">${'<div class="ap-sk">'+Lt("28px",28)+Lt("40%",12)+"</div>"}${'<div class="ap-sk">'+Lt("28px",28)+Lt("55%",12)+"</div>"}</div>`}function Pp(n){if(!ge)return;const e=di(),t=`<nav class="ap-crumb" aria-label="Breadcrumb"><a class="ap-back" href="/agents" data-nav="">${E1}Agents</a></nav>`;if(!e){const a=D.keysDeleted.find(r=>r.id===ge.id);ge.root.innerHTML=`${t}<div class="ap-card ap-nf"><h1 tabindex="-1">${a?`${b($t(a))} was deleted`:"No agent at this address"}</h1>
2870
2870
  <p>${a?"Its key stopped working. You can restore it until you reload the app.":`There is no agent with the key id <code>${b(ge.id)}</code>. It may have been deleted; its past calls stay in Activity.`}</p><div class="acts">${a?`<button type="button" class="btn primary" data-restore>${C1}Restore</button>`:""}
@@ -2877,7 +2877,7 @@ export MEMORA_KEY=${t}`,rules:"<code>AGENTS.md</code> in the project, or <code>~
2877
2877
  aria-label="${O(`${cn(n.action)}${i.length?" "+i.join(", "):a?" "+a:""}${n.ok===!1?", failed":""}, ${ii(n.ts)}`)}">
2878
2878
  <span class="ap-ev-ic" style="--c:${hs[t]}">${oC[t]}</span>
2879
2879
  <span class="ap-ev-m"><b>${b(cn(n.action))}</b>${i.map(r=>`<button type="button" class="ap-ev-p" data-note="${O(r)}" title="${O(r)}">${de.note}<span>${b(bt(r))}</span></button>`).join("")}${n.paths.length>2?`<span class="ap-ev-more">+${n.paths.length-2}</span>`:""}${!i.length&&a?`<span class="ap-ev-l" title="${O(a)}">${b(a)}</span>`:""}</span>${s}
2880
- <span class="ap-ev-t" title="${O(ii(n.ts))}">${e?`<span class="clk">${py(n.ts)}</span>`:""}${o==="now"?"now":o+" ago"}</span></li>`}function Ip(n){return Array.from({length:n},(e,t)=>`<div class="ap-sk">${Lt("28px",28)}${Lt(30+t*17%40+"%",12)}</div>`).join("")}function vC(n,e){const t=$t(e),i=co(e),a=lo(e),s=ds(e),o=s.id?Xi(s.id):void 0,r=xp(e),l=fp(r),c=Tt.oauth.has(e.id),p=a?.last||0,h=r.scopes.map(f=>{const v=up.find(g=>g.id===f);return`<span class="ap-chip${f==="admin"?" admin":""}" title="${O(v.label)}">${b(v.short)}</span>`}).join(""),d=i.st==="off"?`<div class="ap-ban off"><span class="ic">${wp}</span><span class="tx"><b>${b(t)} is turned off</b><small>Its key is refused until you turn it back on. Nothing is deleted.</small></span>
2880
+ <span class="ap-ev-t" title="${O(ii(n.ts))}">${e?`<span class="clk">${py(n.ts)}</span>`:""}${o==="now"?"now":o+" ago"}</span></li>`}function Ip(n){return Array.from({length:n},(e,t)=>`<div class="ap-sk">${Lt("28px",28)}${Lt(30+t*17%40+"%",12)}</div>`).join("")}function vC(n,e){const t=$t(e),i=co(e),a=lo(e),s=ds(e),o=s.id?Xi(s.id):void 0,r=xp(e),l=fp(r),c=Et.oauth.has(e.id),p=a?.last||0,h=r.scopes.map(f=>{const v=up.find(g=>g.id===f);return`<span class="ap-chip${f==="admin"?" admin":""}" title="${O(v.label)}">${b(v.short)}</span>`}).join(""),d=i.st==="off"?`<div class="ap-ban off"><span class="ic">${wp}</span><span class="tx"><b>${b(t)} is turned off</b><small>Its key is refused until you turn it back on. Nothing is deleted.</small></span>
2881
2881
  <button type="button" class="btn" data-o="toggle">${de.check}Turn on</button></div>`:i.st==="never"?`<div class="ap-ban"><span class="ic">${de.plug}</span><span class="tx"><b>No calls yet</b><small>${o?`Follow the ${b(o.label)} setup guide to connect it.`:"Pick its app, then follow the setup guide to connect it."}</small></span><button type="button" class="btn primary" data-o="setup">${de.plug}Open the setup guide</button></div>`:"";n.innerHTML=`${d}
2882
2882
  <div class="ap-stats">
2883
2883
  <div class="ap-stat"><span class="k">Calls in 24h</span><span class="v">${a?a.day:0}${a&&a.day?`<span class="sp">${Nd(a.spark,120,24)}</span>`:""}</span><span class="h">${a&&a.day?"Per hour, last 24 hours":"None in the last 24 hours"}</span></div>
@@ -2900,7 +2900,7 @@ export MEMORA_KEY=${t}`,rules:"<code>AGENTS.md</code> in the project, or <code>~
2900
2900
  </dl></div></section>
2901
2901
  </div>
2902
2902
  </div>`,as(n),n.querySelectorAll("[data-o]").forEach(f=>{f.onclick=()=>f.dataset.o==="toggle"?void bp(e):uo("setup")});const u=n.querySelector("#apRecent");tr(u,f=>ge?.events?.find(v=>v.id===f)),ge.events&&Zm(),Ym(ge.range||"7d")}function Zm(){const n=ge?.root.querySelector("#apRecent");if(!n||!ge.events)return;const e=ge.events.filter(i=>i.source==="agent").slice(0,8),t=di();if(!e.length){n.innerHTML=`<div class="ap-empty"><b>No calls in the last ${ge.range==="7d"?"7 days":"while"}</b>${co(t).st==="never"?"Once its app is set up, every call shows up here as it happens.":"New calls show up here as they happen."}</div>`;return}n.innerHTML=`<ul class="ap-evs" aria-label="Recent calls">${e.map(i=>ow(i)).join("")}</ul>`}function $p(n,e){ge.wizard?.destroy(),ge.wizard=null;const t=$t(e),i=ds(e);if(!i.id||ge.picking)return xC(n,e);if(i.guessed){const c=Xi(i.id);n.innerHTML=`<div class="ap-card ap-ask"><div class="ap-guess">${li(c.label,48)}<span class="tx">
2903
- <h2 tabindex="-1">Is ${b(t)} for ${b(c.label)}?</h2><p style="margin:4px 0 0;font-size:13px;color:var(--muted);line-height:1.55">Guessed from its ${Tt.oauth.has(e.id)?"sign-in":"name"}. Confirm it to see the ${b(c.label)} setup guide. Each agent belongs to one app, so this is asked only once.</p></span>
2903
+ <h2 tabindex="-1">Is ${b(t)} for ${b(c.label)}?</h2><p style="margin:4px 0 0;font-size:13px;color:var(--muted);line-height:1.55">Guessed from its ${Et.oauth.has(e.id)?"sign-in":"name"}. Confirm it to see the ${b(c.label)} setup guide. Each agent belongs to one app, so this is asked only once.</p></span>
2904
2904
  <span class="acts"><button type="button" class="btn primary" data-yes>${de.check}Yes, it's ${b(c.label)}</button>
2905
2905
  <button type="button" class="btn" data-other>Pick another</button></span></div></div>`,n.querySelector("[data-yes]").onclick=()=>{Jm(e,i.id)},n.querySelector("[data-other]").onclick=()=>{ge.picking=!0,$p(n,e),n.querySelector("#apPq")?.focus()};return}const a=Xi(i.id);n.innerHTML=`<div class="ap-card ap-lock">${li(a.label,40)}<span class="tx"><b>${b(a.label)}${R1}</b>
2906
2906
  <small>Each agent belongs to one app. To use Memora in another app, create a separate agent for it.</small></span>
@@ -2930,7 +2930,7 @@ export MEMORA_KEY=${t}`,rules:"<code>AGENTS.md</code> in the project, or <code>~
2930
2930
  <div id="apLive" style="display:flex;flex-direction:column;gap:16px;min-width:0"></div>
2931
2931
  <section class="ap-card ap-danger full"><div class="ap-card-h"><h2>Danger zone</h2></div>
2932
2932
  <div class="ap-row"><span class="tx"><b>Delete this agent</b><small>Its key stops working at once. Past activity stays; you can restore it until you reload the app.</small></span>
2933
- <button type="button" class="btn danger" data-s="delete">${yp}Delete agent</button></div></section></div>`;const t=n.querySelector("#apName"),i=t.querySelector("#apN"),a=()=>{const s=i.value.trim()||$t(e),o=t.querySelector("#apColor").dataset.value;t.querySelector("#apPrev").innerHTML=wC(s,o||vn(s,null),o?"Chosen colour":"Automatic colour from the name")};n0(t,"apColor",a),i.oninput=a,a(),t.onsubmit=async s=>{s.preventDefault();const o=di()||e,r=i.value.trim(),l=t.querySelector("#apColor").dataset.value||"";if(!r){He("The name cannot be empty","warn"),i.focus();return}if(r===(o.name||"")&&l===(o.color||"")){He("Nothing to save","info",1600);return}try{r!==(o.name||"")&&await ht(cs.update,{id:o.id,name:r}),l!==(o.color||"")&&await ht(cs.update,{id:o.id,color:l}),He("Saved","ok"),await Wf(),await Fn(!0)}catch(c){He("Could not save: "+c.message,"err")}},n.querySelector("[data-s=delete]").onclick=()=>Em(di()||e,()=>Ki("")),rw()}function rw(){const n=ge?.root.querySelector("#apLive"),e=di();if(!n||!e)return;const t=e.enabled===!1,i=Tt.oauth.has(e.id);n.innerHTML=`<section class="ap-card"><div class="ap-card-h"><h2>Key</h2></div>
2933
+ <button type="button" class="btn danger" data-s="delete">${yp}Delete agent</button></div></section></div>`;const t=n.querySelector("#apName"),i=t.querySelector("#apN"),a=()=>{const s=i.value.trim()||$t(e),o=t.querySelector("#apColor").dataset.value;t.querySelector("#apPrev").innerHTML=wC(s,o||vn(s,null),o?"Chosen colour":"Automatic colour from the name")};n0(t,"apColor",a),i.oninput=a,a(),t.onsubmit=async s=>{s.preventDefault();const o=di()||e,r=i.value.trim(),l=t.querySelector("#apColor").dataset.value||"";if(!r){He("The name cannot be empty","warn"),i.focus();return}if(r===(o.name||"")&&l===(o.color||"")){He("Nothing to save","info",1600);return}try{r!==(o.name||"")&&await ht(cs.update,{id:o.id,name:r}),l!==(o.color||"")&&await ht(cs.update,{id:o.id,color:l}),He("Saved","ok"),await Wf(),await Fn(!0)}catch(c){He("Could not save: "+c.message,"err")}},n.querySelector("[data-s=delete]").onclick=()=>Em(di()||e,()=>Ki("")),rw()}function rw(){const n=ge?.root.querySelector("#apLive"),e=di();if(!n||!e)return;const t=e.enabled===!1,i=Et.oauth.has(e.id);n.innerHTML=`<section class="ap-card"><div class="ap-card-h"><h2>Key</h2></div>
2934
2934
  <div class="ap-row"><span class="tx"><b>Key ID</b><code>${b(e.id)}</code></span><button type="button" class="cc-ibtn" data-copy="${O(e.id)}" aria-label="Copy the key ID" title="Copy">${de.copy}</button></div>
2935
2935
  <div class="ap-row"><span class="tx"><b>${e.revealable?"Stored sealed":i?"Held by the app":"Shown once"}</b><small>${e.revealable?"Your password shows it again.":i?"The app signed in and holds its own token.":"It was shown when it was made. Make a new key to see one again."}</small></span>${e.revealable?`<button type="button" class="btn" data-s="reveal">${kp}Show key</button>`:""}</div>
2936
2936
  <div class="ap-row"><span class="tx"><b>Make a new key</b><small>The current key stops working at once; the setup guide gets the new one.</small></span>
@@ -3003,7 +3003,7 @@ export MEMORA_KEY=${t}`,rules:"<code>AGENTS.md</code> in the project, or <code>~
3003
3003
  <aside class="an-side" aria-label="Summary"><div class="ap-card an-sum"><h2>Summary</h2><dl id="anSum"></dl>
3004
3004
  <div class="an-open"><button type="button" class="btn primary" id="anOpen" hidden>Open the agent ${de.arrow}</button></div></div>
3005
3005
  <div class="an-tip">${MC}<span><b>Why one agent per app?</b>Activity shows which app did what, and turning one off or making it a new key never touches the others.</span></div></aside>
3006
- </div></div>`,ps(n),n.querySelector("h1")?.focus({preventScroll:!0});const t=n.firstElementChild;if(await Promise.all([ym(),Tt.loaded?null:Fn()]),!t.isConnected)return;const i=t.querySelector("#anBack"),a=t.querySelector("#anNext"),s=t.querySelector("#anWz"),o=x1(s,{client:e||void 0,names:Tt.keys.map($t),existing:Tt.keys.map(r=>({name:$t(r),app:ds(r).id})),createAgent:_1,onAppChosen:(r,l)=>{Sm(r,l)},onChange:()=>{Fn(!0)},setNav:r=>{i.style.visibility=r.back?"":"hidden",a.textContent=r.next,a.title=r.next==="Done"?"Open the new agent":""},onInfo:r=>eg(t,r),onOpenAgent:r=>Ki(r)});vr=o,i.onclick=()=>o.back(),a.onclick=async()=>{a.disabled=!0;try{if(!await o.next())return;const r=o.info(),l=r.agent?.id||r.connectedId;Ki(l||"")}finally{a.disabled=!1}},s.addEventListener("input",()=>eg(t,o.info())),s.addEventListener("click",()=>setTimeout(()=>vr===o&&eg(t,o.info()),0)),Ll(n,()=>()=>{o.destroy(),vr===o&&(vr=null)})}function eg(n,e){const t=n.querySelector("#anSum"),i=n.querySelector("#anStrip");if(!t||!i)return;const a=e.client,s=e.step!=="app"&&!!a,o=(c,p,h,d)=>`<div class="it">${c}<span class="tx"><dt>${p}</dt><dd class="${d?"none":""}">${h}</dd></span></div>`;t.innerHTML=o(li(a?a.label:"",30),"App",a?b(a.label):"Not chosen yet",!a)+o(e.agent?qt(e.agent.name,30,"",e.agent.id):`<span class="ph">${SC}</span>`,"Name",s&&e.name?b(e.name):"Next step",!(s&&e.name))+o(`<span class="ph">${de.shield}</span>`,"Access",s&&e.access?b(e.access):"Next step",!(s&&e.access))+o(`<span class="ph">${de.key}</span>`,"Key",e.agent?`Made · <span class="cc-mono">${b(e.agent.id)}</span>`:a?.oauth?"None: it signs in":"Made when you continue",!e.agent)+(e.step==="setup"||e.step==="prompt"?o(`<span class="ph${e.connected?" ok":""}">${e.connected?de.check:de.plug}</span>`,"Connection",e.connected?"Connected":"Waiting for the first call",!e.connected):"");const r=n.querySelector("#anOpen"),l=e.agent?.id||e.connectedId;r&&(r.hidden=!(e.connected&&l),r.onclick=()=>l&&Ki(l)),i.innerHTML=a?`<span>${li(a.label,22)}<b>${b(a.label)}</b></span>${s&&e.name?`<span>·<b title="${O(e.name)}">${b(e.name)}</b></span>`:""}${s&&e.access?`<span>·<b>${b(e.access)}</b></span>`:""}`:""}const TC=`
3006
+ </div></div>`,ps(n),n.querySelector("h1")?.focus({preventScroll:!0});const t=n.firstElementChild;if(await Promise.all([ym(),Et.loaded?null:Fn()]),!t.isConnected)return;const i=t.querySelector("#anBack"),a=t.querySelector("#anNext"),s=t.querySelector("#anWz"),o=x1(s,{client:e||void 0,names:Et.keys.map($t),existing:Et.keys.map(r=>({name:$t(r),app:ds(r).id})),createAgent:_1,onAppChosen:(r,l)=>{Sm(r,l)},onChange:()=>{Fn(!0)},setNav:r=>{i.style.visibility=r.back?"":"hidden",a.textContent=r.next,a.title=r.next==="Done"?"Open the new agent":""},onInfo:r=>eg(t,r),onOpenAgent:r=>Ki(r)});vr=o,i.onclick=()=>o.back(),a.onclick=async()=>{a.disabled=!0;try{if(!await o.next())return;const r=o.info(),l=r.agent?.id||r.connectedId;Ki(l||"")}finally{a.disabled=!1}},s.addEventListener("input",()=>eg(t,o.info())),s.addEventListener("click",()=>setTimeout(()=>vr===o&&eg(t,o.info()),0)),Ll(n,()=>()=>{o.destroy(),vr===o&&(vr=null)})}function eg(n,e){const t=n.querySelector("#anSum"),i=n.querySelector("#anStrip");if(!t||!i)return;const a=e.client,s=e.step!=="app"&&!!a,o=(c,p,h,d)=>`<div class="it">${c}<span class="tx"><dt>${p}</dt><dd class="${d?"none":""}">${h}</dd></span></div>`;t.innerHTML=o(li(a?a.label:"",30),"App",a?b(a.label):"Not chosen yet",!a)+o(e.agent?qt(e.agent.name,30,"",e.agent.id):`<span class="ph">${SC}</span>`,"Name",s&&e.name?b(e.name):"Next step",!(s&&e.name))+o(`<span class="ph">${de.shield}</span>`,"Access",s&&e.access?b(e.access):"Next step",!(s&&e.access))+o(`<span class="ph">${de.key}</span>`,"Key",e.agent?`Made · <span class="cc-mono">${b(e.agent.id)}</span>`:a?.oauth?"None: it signs in":"Made when you continue",!e.agent)+(e.step==="setup"||e.step==="prompt"?o(`<span class="ph${e.connected?" ok":""}">${e.connected?de.check:de.plug}</span>`,"Connection",e.connected?"Connected":"Waiting for the first call",!e.connected):"");const r=n.querySelector("#anOpen"),l=e.agent?.id||e.connectedId;r&&(r.hidden=!(e.connected&&l),r.onclick=()=>l&&Ki(l)),i.innerHTML=a?`<span>${li(a.label,22)}<b>${b(a.label)}</b></span>${s&&e.name?`<span>·<b title="${O(e.name)}">${b(e.name)}</b></span>`:""}${s&&e.access?`<span>·<b>${b(e.access)}</b></span>`:""}`:""}const TC=`
3007
3007
  .ky{container:ky/inline-size}
3008
3008
  .ky a.btn{text-decoration:none}
3009
3009
 
@@ -3146,17 +3146,17 @@ export MEMORA_KEY=${t}`,rules:"<code>AGENTS.md</code> in the project, or <code>~
3146
3146
  `;function EC(n){const e=n.replace(/\/+$/,"").split("/").slice(2).map(t=>{try{return decodeURIComponent(t)}catch{return""}});return!e.length||!e[0]?{kind:"list"}:e[0]==="new"?{kind:"new",client:e[1]&&Xi(e[1])?e[1]:""}:{kind:"agent",id:e[0],tab:e[1]||"overview"}}function lw(n=""){Zu("/agents/new"+(n?"/"+n:""))}async function CC(){wa(),bm(),at("agents-sheet-css",c3);const n=U("#view-keys"),e=EC(location.pathname),t=e.kind==="agent"?"agent:"+e.id:e.kind;return n.dataset.mode!==t&&(n.dataset.mode=t,n.scrollTop=0),e.kind==="new"?AC(n,e.client):e.kind==="agent"?rC(n,e.id,e.tab):RC(n)}async function RC(n){at("keys-css-4",TC),n.innerHTML=`<div class="cc ky">
3147
3147
  ${Pl("keys","Agents & API keys","Each agent is one API key used by one app. Give every app or device its own agent, so Activity shows exactly who did what.",`<button type="button" class="cc-ibtn" id="kReload" aria-label="Reload" title="Reload">${de.refresh}</button>
3148
3148
  <a class="btn primary" id="kNew" href="/agents/new" data-nav="new">${de.plus}New agent</a>`)}
3149
- <div class="ky-sum" id="kStats" aria-live="polite">${tg(Tt.loaded?Tt.keys:null)}</div>
3149
+ <div class="ky-sum" id="kStats" aria-live="polite">${tg(Et.loaded?Et.keys:null)}</div>
3150
3150
  <div class="ky-h"><h2>Agents</h2><span id="kCount"></span></div>
3151
3151
  <div class="kl" id="kList" aria-busy="true">${LC()}</div>
3152
- <div id="kDel"></div></div>`,ps(n),U("#kReload").onclick=()=>{U("#kReload").classList.add("spin"),Fn(!0)},as(U("#kStats")),Ll(n,()=>{let e=0;const t=Nl((s,o)=>{k1(o)&&!e&&(e=window.setTimeout(()=>(e=0,Np()),800))}),i=w1(()=>Np()),a=window.setInterval(()=>Np(),3e4);return()=>{t(),i(),clearTimeout(e),clearInterval(a)}}),Tt.loaded&&Np(),await Fn(!0)}function LC(){return Array.from({length:4},()=>`<div class="ky-sk">${Lt("32px",32)}<span style="flex:1">${Lt("28%",11)}</span><span style="flex:1">${Lt("40%",10)}</span></div>`).join("")}function Np(){const n=document.getElementById("kList");if(!(!n||!document.querySelector("#view-keys .ky"))){if(document.getElementById("kReload")?.classList.remove("spin"),!Tt.loaded&&Tt.error){U("#kStats").innerHTML=tg(null),n.removeAttribute("aria-busy"),n.innerHTML=`<div class="ky-err"><b>Could not load the agents</b>${b(Tt.error)}
3153
- <div style="margin-top:14px"><button type="button" class="btn" id="kRetry">${de.refresh}Try again</button></div></div>`,U("#kRetry").onclick=()=>{Fn(!0)};return}Tt.loaded&&(U("#kStats").innerHTML=tg(Tt.keys),as(U("#kStats")),IC(n),NC())}}function tg(n){const e=mp(),t=`<div class="ky-st ky-ep"><span class="k">MCP endpoint</span><span class="row"><code title="${O(e)}">${b(e)}</code>
3152
+ <div id="kDel"></div></div>`,ps(n),U("#kReload").onclick=()=>{U("#kReload").classList.add("spin"),Fn(!0)},as(U("#kStats")),Ll(n,()=>{let e=0;const t=Nl((s,o)=>{k1(o)&&!e&&(e=window.setTimeout(()=>(e=0,Np()),800))}),i=w1(()=>Np()),a=window.setInterval(()=>Np(),3e4);return()=>{t(),i(),clearTimeout(e),clearInterval(a)}}),Et.loaded&&Np(),await Fn(!0)}function LC(){return Array.from({length:4},()=>`<div class="ky-sk">${Lt("32px",32)}<span style="flex:1">${Lt("28%",11)}</span><span style="flex:1">${Lt("40%",10)}</span></div>`).join("")}function Np(){const n=document.getElementById("kList");if(!(!n||!document.querySelector("#view-keys .ky"))){if(document.getElementById("kReload")?.classList.remove("spin"),!Et.loaded&&Et.error){U("#kStats").innerHTML=tg(null),n.removeAttribute("aria-busy"),n.innerHTML=`<div class="ky-err"><b>Could not load the agents</b>${b(Et.error)}
3153
+ <div style="margin-top:14px"><button type="button" class="btn" id="kRetry">${de.refresh}Try again</button></div></div>`,U("#kRetry").onclick=()=>{Fn(!0)};return}Et.loaded&&(U("#kStats").innerHTML=tg(Et.keys),as(U("#kStats")),IC(n),NC())}}function tg(n){const e=mp(),t=`<div class="ky-st ky-ep"><span class="k">MCP endpoint</span><span class="row"><code title="${O(e)}">${b(e)}</code>
3154
3154
  <button type="button" class="cc-ibtn" data-copy="${O(e)}" aria-label="Copy the MCP endpoint" title="Copy">${de.copy}</button></span></div>`;if(!n){const c=p=>`<div class="ky-st"><span class="k">${p}</span><span class="v">${Lt("38px",22)}</span></div>`;return c("Agents")+c("Active now")+c("Calls in 24h")+t}const i=Date.now()/1e3,a=n.filter(c=>c.enabled!==!1),s=a.filter(c=>co(c,i).st==="active").length,o=new Array(24).fill(0);for(const c of n)lo(c)?.spark.forEach((p,h)=>o[h]+=p);const r=o.reduce((c,p)=>c+p,0),l=n.length-a.length;return`<div class="ky-st"><span class="k">Agents</span><span class="v">${n.length}${n.length?`<small>${l?`${a.length} on · ${l} off`:"all on"}</small>`:""}</span></div>
3155
3155
  <div class="ky-st"><span class="k">Active now</span><span class="v">${s}${s?'<span class="ky-live" aria-hidden="true"></span>':""}</span></div>
3156
- <div class="ky-st"><span class="k">Calls in 24h</span><span class="v">${r}${r?`<span class="sp">${Nd(o,72,22)}</span>`:""}</span></div>${t}`}function PC(){const n=e=>e.enabled===!1?2:lo(e)||e.uses?0:1;return[...Tt.keys].sort((e,t)=>n(e)-n(t)||(lo(t)?.last||0)-(lo(e)?.last||0)||$t(e).localeCompare($t(t)))}function IC(n){const e=Tt.keys;n.removeAttribute("aria-busy");const t=e.filter(a=>a.enabled!==!1).length;if(U("#kCount").textContent=e.length?`${e.length} · ${t===e.length?"all turned on":`${e.length-t} turned off`}`:"",!e.length){const a=["claude-code","cursor","claude-ai","chatgpt","codex"].map(s=>Xi(s)).filter(Boolean).map(s=>`<a href="${O(pr("new/"+s.id))}" data-nav="new/${O(s.id)}">${li(s.label,26)}${b(s.label)}</a>`).join("");n.innerHTML=`<div class="ky-empty"><span class="ic">${de.plug}</span><h3>No agents yet</h3>
3156
+ <div class="ky-st"><span class="k">Calls in 24h</span><span class="v">${r}${r?`<span class="sp">${Nd(o,72,22)}</span>`:""}</span></div>${t}`}function PC(){const n=e=>e.enabled===!1?2:lo(e)||e.uses?0:1;return[...Et.keys].sort((e,t)=>n(e)-n(t)||(lo(t)?.last||0)-(lo(e)?.last||0)||$t(e).localeCompare($t(t)))}function IC(n){const e=Et.keys;n.removeAttribute("aria-busy");const t=e.filter(a=>a.enabled!==!1).length;if(U("#kCount").textContent=e.length?`${e.length} · ${t===e.length?"all turned on":`${e.length-t} turned off`}`:"",!e.length){const a=["claude-code","cursor","claude-ai","chatgpt","codex"].map(s=>Xi(s)).filter(Boolean).map(s=>`<a href="${O(pr("new/"+s.id))}" data-nav="new/${O(s.id)}">${li(s.label,26)}${b(s.label)}</a>`).join("");n.innerHTML=`<div class="ky-empty"><span class="ic">${de.plug}</span><h3>No agents yet</h3>
3157
3157
  <p>Make an agent for each app or device you use. Each one gets its own key, so you can see what it does and turn it off on its own.</p>
3158
3158
  <a class="btn primary" href="/agents/new" data-nav="new">${de.plus}New agent</a><div class="ky-pop" aria-label="Popular apps">${a}</div></div>`,ps(n);return}const i=Date.now()/1e3;n.innerHTML=`<div class="kl-head" aria-hidden="true"><span>Agent</span><span>App</span><span>Status</span><span>Access</span><span>Calls 24h</span><span>Last call</span><span></span></div>
3159
- <ul aria-label="Agents">${PC().map(a=>$C(a,i)).join("")}</ul>`,ps(n),Kn("[data-more]",n).forEach(a=>a.onclick=s=>{s.stopPropagation();const o=Tt.keys.find(r=>r.id===a.dataset.more);o&&DC(a,o)})}function $C(n,e){const t=$t(n),i=co(n,e),a=lo(n),s=ds(n),o=fp(xp(n)),r=Tt.oauth.has(n.id)?'<span class="tag">Signed in</span>':"",l=a?a.day:0;return`<li class="kr${i.st==="off"?" off":""}" style="--ag:${vn(t,n.id)}">
3159
+ <ul aria-label="Agents">${PC().map(a=>$C(a,i)).join("")}</ul>`,ps(n),Kn("[data-more]",n).forEach(a=>a.onclick=s=>{s.stopPropagation();const o=Et.keys.find(r=>r.id===a.dataset.more);o&&DC(a,o)})}function $C(n,e){const t=$t(n),i=co(n,e),a=lo(n),s=ds(n),o=fp(xp(n)),r=Et.oauth.has(n.id)?'<span class="tag">Signed in</span>':"",l=a?a.day:0;return`<li class="kr${i.st==="off"?" off":""}" style="--ag:${vn(t,n.id)}">
3160
3160
  <a class="kr-hit" href="${O(pr(n.id))}" data-nav="${O(n.id)}" aria-label="${O(`${t}: ${i.label}, ${s.label||"app not set"}, ${o.level}`)}"></a>
3161
3161
  <div class="kr-agent">${qt(t,34,"",n.id)}<span class="t"><b>${b(t)}${r}</b><span class="kid">${b(n.id)}</span>
3162
3162
  <span class="sub2"><span class="app">${b(s.label||"App not set")} · </span>${b(o.level)}</span></span></div>
@@ -9342,6 +9342,7 @@ html[data-theme=light] .cv{
9342
9342
 
9343
9343
  <p align="center">
9344
9344
  <a href="https://github.com/Codrihub/memora/releases/latest"><img src="https://img.shields.io/github/v/release/Codrihub/memora?sort=semver" alt="Latest release"></a>
9345
+ <a href="https://www.npmjs.com/package/@codrihub/memora"><img src="https://img.shields.io/npm/v/@codrihub/memora?logo=npm&label=npm" alt="npm: @codrihub/memora"></a>
9345
9346
  <a href="https://github.com/Codrihub/memora/actions/workflows/ci.yml"><img src="https://github.com/Codrihub/memora/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
9346
9347
  <a href="LICENSE"><img src="https://img.shields.io/github/license/Codrihub/memora" alt="License: MIT"></a>
9347
9348
  <a href="https://github.com/Codrihub/memora/pkgs/container/memora"><img src="https://img.shields.io/badge/ghcr.io-codrihub%2Fmemora-blue?logo=docker" alt="Docker image"></a>
@@ -9351,9 +9352,12 @@ html[data-theme=light] .cv{
9351
9352
  <a href="https://memora.codrihub.tech">Website</a> ·
9352
9353
  <a href="https://memora.codrihub.tech/docs">Documentation</a> ·
9353
9354
  <a href="#quick-start">Quick start</a> ·
9355
+ <a href="https://www.npmjs.com/package/@codrihub/memora">npm</a> ·
9354
9356
  <a href="https://github.com/Codrihub/memora/releases">Releases</a>
9355
9357
  </p>
9356
9358
 
9359
+ <p align="center"><code>npm install -g @codrihub/memora</code></p>
9360
+
9357
9361
  Memora is a self-hosted memory vault for AI agents. Notes are plain markdown
9358
9362
  files in a git-backed folder. Agents read and write them over the Model Context
9359
9363
  Protocol (MCP); you browse, edit and govern them in a web UI. One Rust binary
@@ -9399,26 +9403,31 @@ Screenshots use a demo vault.
9399
9403
 
9400
9404
  Three steps, about two minutes.
9401
9405
 
9402
- **1. Install** (pick one)
9406
+ **1. Install** (pick one, in this order of ease)
9403
9407
 
9404
9408
  \`\`\`bash
9405
- # Linux server with systemd (x86_64 or aarch64)
9406
- curl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh
9409
+ # npm (Linux x86_64 / arm64, Windows x64; Node 18+): install, then keep it running
9410
+ npm install -g @codrihub/memora && memora
9407
9411
 
9408
- # or anywhere with Docker
9412
+ # Docker (any OS with Docker)
9409
9413
  docker run -d --name memora --restart unless-stopped -p 8400:8400 \\
9410
9414
  -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest
9411
9415
 
9412
- # or with npm (Linux x86_64 / arm64, Node 18+), then keep it running
9413
- npm install -g @codrihub/memora && memora
9416
+ # Native installer (Linux server with systemd, x86_64 or aarch64)
9417
+ curl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh
9414
9418
  \`\`\`
9415
9419
 
9420
+ On Windows without Node, download \`memora-<version>-x86_64-windows.zip\` from
9421
+ [Releases](https://github.com/Codrihub/memora/releases/latest), unzip it and run
9422
+ \`memora.exe\` (see [Windows](#windows-zip-no-node)).
9423
+
9416
9424
  **2. Get a one-time setup code**
9417
9425
 
9418
9426
  \`\`\`bash
9419
- sudo memora-cli setup --minutes 15 # native
9420
- docker exec -it memora memora-cli setup --minutes 15 # Docker
9421
9427
  memora-cli setup --minutes 15 # npm, in a second terminal
9428
+ docker exec -it memora memora-cli setup --minutes 15 # Docker
9429
+ sudo memora-cli setup --minutes 15 # native
9430
+ .\\memora-cli.exe setup --minutes 15 # Windows zip, in the unzipped folder
9422
9431
  \`\`\`
9423
9432
 
9424
9433
  **3. Open the link it prints** (\`http://<your-server>:8400/login\`), enter the code
@@ -9427,14 +9436,67 @@ shows how to connect your first agent.
9427
9436
 
9428
9437
  That is all. The sections below cover every other option.
9429
9438
 
9430
- ### Docker Compose
9439
+ ### npm (Linux x86_64 / arm64, Windows x64)
9440
+
9441
+ \`\`\`bash
9442
+ npm install -g @codrihub/memora
9443
+ mkdir -p ~/memora && cd ~/memora
9444
+ MEMORA_VAULT=./vault MEMORA_STATE=./state memora
9445
+ # in a second terminal, same folder:
9446
+ MEMORA_STATE=./state memora-cli setup --minutes 15
9447
+ \`\`\`
9448
+
9449
+ On Windows (PowerShell):
9450
+
9451
+ \`\`\`powershell
9452
+ npm install -g @codrihub/memora
9453
+ mkdir ~\\memora; cd ~\\memora
9454
+ $env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; memora
9455
+ # in a second terminal, same folder:
9456
+ $env:MEMORA_STATE = '.\\state'; memora-cli setup --minutes 15
9457
+ \`\`\`
9458
+
9459
+ The package carries the prebuilt release binaries and the web UI (no install
9460
+ script, nothing downloaded at install time) and needs Node 18 or newer. It is
9461
+ handy for trying Memora or running it under your own user; for a server, the
9462
+ native installer adds the systemd service. On macOS use Docker or build from
9463
+ source. Update with \`npm install -g @codrihub/memora@latest\`.
9464
+
9465
+ ### Windows (zip, no Node)
9466
+
9467
+ Each release has a \`memora-<version>-x86_64-windows.zip\` with \`memora.exe\`,
9468
+ \`memora-cli.exe\` and the web UI. Unzip it anywhere, then in PowerShell:
9469
+
9470
+ \`\`\`powershell
9471
+ cd memora-<version>-x86_64-windows
9472
+ $env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; .\\memora.exe
9473
+ # in a second PowerShell window, same folder:
9474
+ $env:MEMORA_STATE = '.\\state'; .\\memora-cli.exe setup --minutes 15
9475
+ \`\`\`
9476
+
9477
+ Open \`http://localhost:8400/login\` and enter the code. The binaries need no
9478
+ installer or runtime; check the zip against \`SHA256SUMS\` from the same release
9479
+ (\`Get-FileHash memora-*.zip\`).
9480
+
9481
+ ### Docker (any OS)
9482
+
9483
+ One container, notes and state in named volumes (no clone, no folder
9484
+ permissions):
9485
+
9486
+ \`\`\`bash
9487
+ docker run -d --name memora --restart unless-stopped -p 8400:8400 \\
9488
+ -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest
9489
+ docker exec -it memora memora-cli setup --minutes 15
9490
+ \`\`\`
9491
+
9492
+ With Docker Compose from the repository instead:
9431
9493
 
9432
9494
  \`\`\`bash
9433
9495
  git clone https://github.com/Codrihub/memora.git && cd memora
9434
9496
  cp .env.example .env # optional, every value has a default
9435
9497
  mkdir -p data state && sudo chown -R 1000:1000 data state
9436
9498
  docker compose up -d
9437
- docker compose exec -it gateway memora-cli # then type /web
9499
+ docker compose exec -it gateway memora-cli setup --minutes 15
9438
9500
  \`\`\`
9439
9501
 
9440
9502
  The image is \`ghcr.io/codrihub/memora\` (linux/amd64 and linux/arm64). See
@@ -9463,22 +9525,6 @@ release \`SHA256SUMS\`, creates a \`memora\` system user, and installs a hardene
9463
9525
  \`sh install.sh --help\` for every option, and see
9464
9526
  [docs/INSTALL.md](docs/INSTALL.md) for details.
9465
9527
 
9466
- ### npm (Linux x86_64 / arm64)
9467
-
9468
- \`\`\`bash
9469
- npm install -g @codrihub/memora
9470
- mkdir -p ~/memora && cd ~/memora
9471
- MEMORA_VAULT=./vault MEMORA_STATE=./state memora
9472
- # in a second terminal, same folder:
9473
- MEMORA_STATE=./state memora-cli # then type /web
9474
- \`\`\`
9475
-
9476
- The package carries the prebuilt release binaries and the web UI (no install
9477
- script, nothing downloaded at install time) and needs Node 18 or newer. It is
9478
- handy for trying Memora or running it under your own user; for a server, the
9479
- native installer adds the systemd service. On macOS and Windows use Docker or
9480
- build from source. Update with \`npm install -g @codrihub/memora@latest\`.
9481
-
9482
9528
  ### From source
9483
9529
 
9484
9530
  \`\`\`bash
@@ -9495,11 +9541,12 @@ service: \`sudo ./scripts/install.sh --from-source\`. The web UI is built from
9495
9541
 
9496
9542
  ### First run
9497
9543
 
9498
- 1. In the console, type \`/web\`. It prints a one-time setup code.
9544
+ 1. Run \`memora-cli setup\` (or type \`/web\` in the \`memora-cli\` console). It
9545
+ prints a one-time setup code and the link to open.
9499
9546
  2. Open \`http://<host>:8400/login\`, enter the code and create the owner account.
9500
9547
  3. Choose the vault folder (\`/var/lib/memora/vault\` natively, \`/data\` in Docker).
9501
- 4. Create an API key for an agent (web UI or \`/keys\` in the console) and
9502
- connect it over MCP (\`/mcp\` in the console prints a ready-made config).
9548
+ 4. Add an agent: Agents, then New agent. Pick the app and paste the config it
9549
+ shows. One agent per app or device.
9503
9550
 
9504
9551
  If a setup window expires unused, the instance locks until you run
9505
9552
  \`memora-cli setup\` or \`memora-cli unlock\` on the server.
@@ -9620,7 +9667,8 @@ scripts/ installer and maintenance scripts
9620
9667
 
9621
9668
  Memora follows [Semantic Versioning](https://semver.org/). Each release is a
9622
9669
  \`vX.Y.Z\` tag with a [GitHub Release](https://github.com/Codrihub/memora/releases)
9623
- (static Linux binaries for x86_64 and aarch64 plus \`SHA256SUMS\`) and a
9670
+ (static Linux binaries for x86_64 and aarch64 plus \`SHA256SUMS\`), npm
9671
+ packages for Linux and Windows, and a
9624
9672
  multi-arch image \`ghcr.io/codrihub/memora:X.Y.Z\`. Changes are listed in
9625
9673
  [CHANGELOG.md](CHANGELOG.md).
9626
9674
 
@@ -9632,7 +9680,7 @@ Contributions are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) and the
9632
9680
  ## License
9633
9681
 
9634
9682
  MIT, see [LICENSE](LICENSE). Memora by Codrihub Tech.
9635
- `,$N="# Installing Memora\n\nMemora ships as two binaries plus a folder of web UI assets:\n\n| Piece | Role |\n|---|---|\n| `memora` | The server: HTTP API, MCP, web UI, and WebSocket on **one TCP port** (default `8400`) |\n| `memora-cli` | The operator console. Run it with no arguments for slash commands (`/guide`, `/web`, `/config`, ...) |\n| `assets/` | Web UI files, found through `MEMORA_ASSETS` |\n\nThere are two supported ways to run it as a service: **native** (systemd, via\n`install.sh`) and **Docker** (Compose). On Linux it can also be installed with\n**npm**, which is handy for trying it or running it under your own user. All\nend the same way: open the console, type `/web`, and finish setup in the\nbrowser.\n\n**Fastest path:** install with one command, run `memora-cli setup`, open the\nlink it prints and enter the code.\n\n```bash\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\nsudo memora-cli setup --minutes 15\n```\n\nWith Docker, no clone or folder permissions needed (named volumes):\n\n```bash\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\ndocker exec -it memora memora-cli setup --minutes 15\n```\n\n- [Network exposure](#network-exposure)\n- [Native install](#native-install)\n- [Docker](#docker)\n- [npm](#npm)\n- [Reverse proxy](#reverse-proxy)\n- [Backups](#backups)\n- [Automation: `--check` and `--upgrade`](#automation---check-and---upgrade)\n\n## Network exposure\n\nMemora opens exactly **one TCP port**. The HTTP API, MCP (`/mcp`), the web UI,\nand the realtime WebSocket (`/ws`) all share it. The local event intake\n`/_bus` answers on the same port but only to loopback clients.\n\nThe state database is embedded SQLite (`<state>/memora.db`). The server creates\nand migrates it on first start; it opens no port and needs no separate\ndatabase server or install.\n\nNothing else listens. Allow only that one port through the firewall, or none at\nall when a reverse proxy on the same host is the entry point\n(`--behind-proxy`).\n\n## Native install\n\nRequirements: Linux on x86_64 or aarch64 with systemd, `curl` (or `wget`),\n`tar`, `sha256sum`, and `git` (vault history uses it).\n\n```sh\n# Inspect first: https://github.com/Codrihub/memora/blob/main/scripts/install.sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nPass flags after `sh -s --`, for example:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh \\\n | sudo sh -s -- --version 1.0.0 --behind-proxy\n```\n\nor download the script and run it: `sudo sh install.sh --help`.\n\nThe script is idempotent: running it again reinstalls the same files and keeps\nthe port and bind address of the existing unit unless you pass new ones.\n\n### What it does\n\n1. Downloads `memora-<version>-<arch>-linux.tar.gz` for this CPU from GitHub\n Releases (the latest, or `--version`), downloads `SHA256SUMS` from the same\n release, and refuses to continue if the checksum does not match.\n2. Installs the binaries atomically (copy to a temp file, then `mv`).\n3. Creates the system user and group `memora` (no login shell, home\n `/var/lib/memora`).\n4. Creates `/var/lib/memora/state` (`0700`) and `/var/lib/memora/vault`\n (`0750`), owned by `memora`.\n5. Writes `/etc/systemd/system/memora.service`, enables and starts it, waits\n for `/healthz`, then verifies the state database with `memora-cli db check`.\n6. Prints the next step and, when listening on every interface, a firewall\n hint.\n\n### Paths\n\n| Path | Content |\n|---|---|\n| `/usr/local/bin/memora`, `/usr/local/bin/memora-cli` | Binaries |\n| `/usr/local/share/memora/assets/` | Web UI |\n| `/usr/local/share/memora/VERSION` | Installed version (read by `--check`) |\n| `/usr/local/share/memora/install.sh` | Copy of the installer, used for `--upgrade`, `--check`, `--uninstall`, and `memora-cli update` |\n| `/var/lib/memora/state/` | `memora.db` (owner, API key hashes, sessions, settings, activity log), `backups/` |\n| `/var/lib/memora/vault/` | Suggested vault folder (chosen in the browser after the first sign-in) |\n| `/etc/systemd/system/memora.service` | The unit |\n\n`--prefix` moves the first four (default `/usr/local`), `--data-dir` moves the\nlast two (default `/var/lib/memora`).\n\n### Flags\n\n| Flag | Meaning |\n|---|---|\n| *(none)* | Install or reinstall the latest release |\n| `--version X.Y.Z` | Install that release |\n| `--from-source` | Build with `cargo build --release --locked` in the checkout the script lives in (`sudo ./scripts/install.sh --from-source`); built as `$SUDO_USER` |\n| `--from-dir PATH` | Install `PATH/memora`, `PATH/memora-cli`, `PATH/assets/` (an unpacked release, or your own build). Version from `--version`, else `PATH/VERSION` |\n| `--port N` | Port (default `8400`) |\n| `--bind ADDR` | Bind address (default `0.0.0.0`) |\n| `--behind-proxy` | Bind `127.0.0.1`; a reverse proxy on this host is the only entry |\n| `--prefix DIR` | Install prefix (default `/usr/local`) |\n| `--data-dir DIR` | Data root (default `/var/lib/memora`) |\n| `--no-start` | Install and enable, but do not start |\n| `--no-systemd` | Skip the unit and the system user (containers, tests); prints the command to start the server by hand |\n| `--upgrade` | Replace binaries and assets, keep state, restart the service if it was running |\n| `--force` | With `--upgrade`: reinstall even when already up to date |\n| `--uninstall` | Stop and remove the unit, binaries, and assets; keep data |\n| `--purge` | With `--uninstall`: also delete the data dir and the `memora` user (asks first) |\n| `--check` | Print `MEMORA_LATEST=` and `MEMORA_INSTALLED=`; change nothing |\n| `--yes`, `-y` | Never ask (needed for `--purge` without a terminal) |\n| `--dry-run` | Print every action, change nothing |\n| `--repo OWNER/NAME` | Download from another GitHub repository (forks); also settable as `MEMORA_REPO` |\n\n`MEMORA_RELEASES_URL` points the installer at a mirror that serves the same\nlayout as GitHub (`<url>/latest`, `<url>/download/vX.Y.Z/<file>`).\n\nRoot is required except for `--check`, `--dry-run`, and `--no-systemd` into a\nprefix you can write to.\n\n### Exit codes\n\n| Code | Meaning |\n|---|---|\n| `0` | Success |\n| `1` | Error (see the message) |\n| `2` | Bad usage |\n| `3` | Already up to date (`--upgrade`) |\n| `4` | Network or download failure |\n| `5` | Checksum mismatch or missing from `SHA256SUMS` |\n| `6` | Not running as root |\n| `7` | Unsupported OS or CPU |\n\n### The systemd unit\n\nThe installer writes this unit (shown with the default paths and port):\n\n```ini\n[Unit]\nDescription=Memora - long-term memory for AI agents (HTTP API + MCP + web UI)\nDocumentation=https://github.com/Codrihub/memora\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=memora\nGroup=memora\nWorkingDirectory=/var/lib/memora\nEnvironment=HOME=/var/lib/memora\nEnvironment=MEMORA_STATE=/var/lib/memora/state\nEnvironment=MEMORA_ASSETS=/usr/local/share/memora/assets\nEnvironment=MEMORA_PORT=8400\nEnvironment=MEMORA_BIND=0.0.0.0\nEnvironment=MEMORA_VAULT=/var/lib/memora/vault\nEnvironment=GIT_AUTHOR_NAME=Memora\nEnvironment=GIT_AUTHOR_EMAIL=memora@localhost\nEnvironment=GIT_COMMITTER_NAME=Memora\nEnvironment=GIT_COMMITTER_EMAIL=memora@localhost\nEnvironment=RUST_LOG=info\nExecStart=/usr/local/bin/memora\nRestart=on-failure\nRestartSec=3\nTimeoutStopSec=15\nLimitNOFILE=65536\nUMask=0027\n\n# Hardening\nNoNewPrivileges=yes\nAmbientCapabilities=\nCapabilityBoundingSet=\nProtectSystem=strict\nReadWritePaths=/var/lib/memora\nProtectHome=yes\nPrivateTmp=yes\nPrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectKernelLogs=yes\nProtectControlGroups=yes\nProtectClock=yes\nProtectHostname=yes\nRestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nRestrictNamespaces=yes\nRestrictRealtime=yes\nRestrictSUIDSGID=yes\nLockPersonality=yes\nMemoryDenyWriteExecute=yes\nSystemCallArchitectures=native\nSystemCallFilter=@system-service\nSystemCallFilter=~@privileged\n\n[Install]\nWantedBy=multi-user.target\n```\n\nA port below 1024 adds `CAP_NET_BIND_SERVICE` instead of the empty capability\nset. There are no IP restrictions (`IPAddressDeny=`) by default; use the\nfirewall, `MEMORA_DOMAIN`, or the access rules in the UI.\n\nThe installer rewrites the unit on every run. Put local changes in a drop-in:\n\n```sh\nsudo systemctl edit memora # for example, a vault outside /var/lib/memora:\n# [Service]\n# ReadWritePaths=/srv/notes\nsudo systemctl restart memora\n```\n\nBecause of `ProtectSystem=strict` and `ProtectHome=yes`, the server can only\nwrite under `/var/lib/memora`. A vault anywhere else (including `/home`) needs\nthe drop-in above (and `ProtectHome=read-only` or `no` for `/home`).\n\n### Settings\n\nThe unit sets the basics (`MEMORA_STATE`, `MEMORA_ASSETS`, `MEMORA_PORT`,\n`MEMORA_BIND`, `MEMORA_VAULT`, `RUST_LOG`) as `Environment=` lines. Everything\nelse (`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`, ...) is\nstored in the state database (table `server_config`). Edit it with the\nconsole: `sudo memora-cli` → `/config`, then `/restart`.\n\nA value stored with `/config` wins over the unit's `Environment=` lines; a key\nwith no stored value uses the environment. If you stored `MEMORA_PORT` with\n`/config` and later reinstall with `--port`, change or clear it in `/config`\ntoo, otherwise the stored value keeps applying. The provisioning owner\npassword and API key are environment-only and never stored (see\n[CONFIGURATION.md](CONFIGURATION.md)).\n\nSee [CONFIGURATION.md](CONFIGURATION.md) for every variable.\n\n### First run\n\n```sh\nsudo memora-cli # opens the console; it finds the running server itself\n/guide # step-by-step, or:\n/web # prints a one-time code\n```\n\nOpen `http://<host>:8400/login`, enter the code, create the owner account, then\nchoose the vault folder (`/var/lib/memora/vault` is suggested).\n\n### Day to day\n\n```sh\nsudo systemctl status memora\nsudo systemctl restart memora\nsudo journalctl -u memora -f\nsudo memora-cli # /status, /keys, /config, /restart, /mcp ...\n```\n\n### Upgrading\n\n```sh\nsudo /usr/local/share/memora/install.sh --upgrade # latest release\nsudo /usr/local/share/memora/install.sh --upgrade --version 1.0.1\nsudo memora-cli update # same, from the console\n```\n\nBinaries and assets are swapped atomically, the state directory and vault are\nuntouched, and the service is restarted if it was running. The server migrates\n`memora.db` itself on start. Take a `memora-cli db backup` before upgrading,\nand read the [CHANGELOG](../CHANGELOG.md) before a major version bump.\n\n### Uninstall\n\n```sh\nsudo /usr/local/share/memora/install.sh --uninstall # keeps /var/lib/memora and the memora user\nsudo /usr/local/share/memora/install.sh --uninstall --purge # also deletes notes, account, keys, and the user\n```\n\n### Firewall\n\nOpen only the Memora port, and only when clients connect directly:\n\n```sh\nsudo ufw allow 8400/tcp\n# or\nsudo firewall-cmd --permanent --add-port=8400/tcp && sudo firewall-cmd --reload\n```\n\nBehind a reverse proxy on the same host, install with `--behind-proxy` and open\nonly the proxy's 80/443.\n\n## Docker\n\n```sh\ngit clone https://github.com/Codrihub/memora.git && cd memora\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ndocker compose exec -it gateway memora-cli # then /guide, or /web\n```\n\n`docker compose up` pulls `ghcr.io/codrihub/memora:<version>`; if the image is\nnot available (or you set `IMAGE=memora:local`) it builds from the\n`Dockerfile`. Image tags: `<version>` (for example `1.0.0`), `<major>.<minor>`\n(for example `1.0`), and `latest` (stable releases only), for `linux/amd64`\nand `linux/arm64`. The compose file pins the release it ships with; set\n`IMAGE` in `.env` to run another tag.\n\n### Volumes: `/data` and `/state`\n\nBoth must be persistent (the Compose file bind-mounts `./data` and `./state`):\n\n- `/data` is the vault: your notes, their git history, the search index, and\n the event log. Lose it and the notes are gone.\n- `/state` holds `memora.db` (owner account, password hash, API key hashes,\n sessions, settings, setup/lock state, activity log). Lose it and\n every agent key stops working, the instance falls back to first-run setup,\n and anyone who reaches the port during that window could claim it.\n\nThe container runs as uid 1000; set `MEMORA_UID`/`MEMORA_GID` in `.env` if the\nhost directories belong to another user. `MEMORA_DATA_DIR` and\n`MEMORA_STATE_DIR` move the host directories, and `MEMORA_HTTP_PORT` changes\nthe published host port. See [CONFIGURATION.md](CONFIGURATION.md#docker-compose-env).\n\n### Verify\n\n```sh\ncurl -s http://127.0.0.1:8400/healthz\ndocker compose exec gateway memora-cli db check\ndocker compose exec gateway memora-cli status\nls -l state/memora.db\n```\n\n### Upgrading\n\n```sh\ngit pull\ndocker compose pull && docker compose up -d # or: docker compose up -d --build\n```\n\nSettings: `docker compose exec -it gateway memora-cli` → `/config`, then\n`docker compose restart gateway` (`/restart` cannot restart a container from\ninside).\n\n## npm\n\nRequirements: Linux on x86_64 or arm64, Node 18 or newer, and `git` (vault\nhistory uses it).\n\n```sh\nnpm install -g @codrihub/memora\nmkdir -p ~/memora && cd ~/memora\nMEMORA_VAULT=./vault MEMORA_STATE=./state memora\n# in a second terminal, same folder:\nMEMORA_STATE=./state memora-cli # then /guide, or /web\n```\n\n`npx @codrihub/memora --version` runs it without a global install.\n\n`@codrihub/memora` holds the `memora` and `memora-cli` commands and the web UI\n(used unless `MEMORA_ASSETS` is set). The binaries come from\n`@codrihub/memora-linux-x64` or `@codrihub/memora-linux-arm64`, optional\ndependencies npm installs only on a matching machine. They are the static\nbinaries of the GitHub release with the same version, so glibc and musl\ndistributions both work. There is no install script and nothing is downloaded\nat install time, so it works with `--ignore-scripts` and from a registry\nmirror; it does not work with `--omit=optional`, which leaves the binaries\nout. On macOS and Windows the commands print where to go instead: use\n[Docker](#docker) or build from source (on Windows, WSL 2 works too).\n\nThe npm install sets up no service, user or data folder: the server runs as\nyou, with `MEMORA_STATE` and `MEMORA_VAULT` where you point them (`./state`\nby default). Keep the state folder private (`chmod 700 state`), since it\nholds the owner account and key hashes. For a long-running server, prefer the\n[native install](#native-install).\n\nUpgrade with `npm install -g @codrihub/memora@latest` (`memora-cli update`\nprints this too) and restart the server; the state database is migrated on\nstart.\n\n## Reverse proxy\n\nRun Memora on loopback (`--behind-proxy` natively; in Docker set\n`MEMORA_HTTP_PORT=127.0.0.1:8400` in `.env`) and let the proxy terminate TLS.\nThen set, with `/config` or in `.env`:\n\n| Variable | Why |\n|---|---|\n| `MEMORA_BASE_URL=https://memory.example.com` | Public URL; links and MCP snippets use it, and its host becomes an allowed domain |\n| `MEMORA_DOMAIN=memory.example.com` | Only these hostnames are served; requests for the bare IP or other names get 404 |\n| `MEMORA_TRUSTED_PROXIES=203.0.113.10` | Proxies whose forwarding headers are believed. Loopback (same-host nginx, cloudflared) is always trusted; only list remote proxies |\n\nIn Docker, a proxy on the host reaches the container through the Docker\nnetwork, so the container sees the network's gateway address (for example\n`172.18.0.1`) instead of loopback. Add that address to\n`MEMORA_TRUSTED_PROXIES`, otherwise every request appears to come from it.\n\nThe proxy must forward `Host`, `X-Forwarded-For`, and `X-Forwarded-Proto`, and\nupgrade WebSockets on `/ws`. nginx and Caddy examples are in\n[DEPLOYMENT.md](DEPLOYMENT.md).\n\n## Backups\n\nBack up **both** the state database and the vault. The database is small but\ncritical.\n\nState, online (the server keeps running):\n\n```sh\nsudo memora-cli db backup # state/backups/memora-<UTC time>.db, keeps the newest 10\nsudo memora-cli db backup --to /var/backups/memora.db\nsudo memora-cli db check # integrity, permissions, sizes, last backup age\ndocker compose exec gateway memora-cli db backup # Docker: lands in ./state/backups/\n```\n\nThe copy is a consistent snapshot (`VACUUM INTO`), checked with\n`integrity_check`, mode 0600. Never `cp` a live `memora.db`: recent commits sit\nin `memora.db-wal`. Restore with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo memora-cli db restore /var/backups/memora.db # verifies it; keeps the replaced DB in state/backups/\nsudo systemctl start memora\n```\n\nAlso keep a copy of `state/key-seal.bin`, which encrypts the sealed API key\ncopies. Vault and state together: archive both with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo tar -C /var/lib/memora -czf memora-backup-$(date +%F).tar.gz state vault\nsudo systemctl start memora\n```\n\nKeep backups private: the database holds password and key hashes (never\nplaintext secrets).\n\n## Automation: `--check` and `--upgrade`\n\nThese are the contract for scripts and automation.\n\n```sh\n$ /usr/local/share/memora/install.sh --check\nMEMORA_LATEST=1.0.1\nMEMORA_INSTALLED=1.0.0\n```\n\n`MEMORA_INSTALLED` comes from `/usr/local/share/memora/VERSION` (written by\nthe installer), else from `memora --version`, else `unknown` (or `none` when\nnothing is installed). `MEMORA_LATEST` is `unknown` and the exit code `4` when\nGitHub cannot be reached. `--check` needs no root.\n\n```sh\n$ sudo /usr/local/share/memora/install.sh --upgrade --yes [--version X.Y.Z]\n...\nMEMORA_UPGRADE_RESULT=ok FROM=1.0.0 TO=1.0.1\n```\n\n`--upgrade --yes` never prompts. The last line of output is always\n`MEMORA_UPGRADE_RESULT=<ok|uptodate|error> FROM=<old> TO=<new>`, and the exit\ncode is `0` (ok), `3` (already up to date), `4` (network), `5` (checksum),\n`6` (not root), or `1`/`2` for other errors.\n",NN="# Configuration\n\nAll server state, settings included, lives in one SQLite database,\n`<MEMORA_STATE>/memora.db` (see [DATABASE.md](DATABASE.md)). Server settings are\nrows in the `server_config` table, edited with `memora-cli` (`/config` in the\nconsole). The process environment (systemd `Environment=`, Docker\n`environment:`) applies to every key that has no row.\n\n## Precedence\n\nFor each server setting:\n\n1. a row in `server_config` (set with `/config`), else\n2. the process environment (non-empty value), else\n3. the built-in default.\n\nThe server reads `server_config` once at startup, before anything else, so a\nchange made with `/config` applies after a restart (`/restart` for a native\ninstall, `docker compose restart gateway` in Docker). Clearing a value in\n`/config` deletes the row, and the environment or default applies again.\n\nA row wins over the environment. If you set `MEMORA_PORT` with `/config` and\nlater change the port in the systemd unit or `.env`, the row still applies\nuntil you clear it.\n\n## Server settings\n\n| Name | Default | Where it can live | What it does |\n|---|---|---|---|\n| `MEMORA_PORT` | `8400` | `server_config` or env | HTTP port (API, MCP, web UI, WebSocket). 1-65535. |\n| `MEMORA_BIND` | `127.0.0.1` | `server_config` or env | Bind address. `0.0.0.0` for every interface (the container image and the installer set it). |\n| `MEMORA_BASE_URL` | empty | `server_config` or env | Public URL, for example `https://memory.example.com`. Used for OAuth metadata and connection snippets; its host is also an allowed domain. |\n| `MEMORA_DOMAIN` | empty (any host) | `server_config` or env | Allowed hostnames, comma separated (`*.example.com` works). Requests for other hosts get 404. Loopback names are always allowed. |\n| `MEMORA_TRUSTED_PROXIES` | empty | `server_config` or env | IPs of remote reverse proxies whose forwarding headers are trusted. Loopback is always trusted. |\n| `MEMORA_ARM_TTL` | `300` | `server_config` or env | Accepted and validated (30-86400 seconds), but the server and `memora-cli` do not read it: the setup / reset window length comes from `memora-cli --minutes` (default 5 minutes). |\n| `MEMORA_VAULT` | empty (`data` as last resort) | `server_config` or env | Suggested vault folder. The vault in use is chosen in the browser (or with `memora-cli vault`) and stored in the `settings` table. |\n| `MEMORA_VAULT_AUTO` | `false` | `server_config` or env | `true` (also `1`, `yes`, `on`): use `MEMORA_VAULT` at startup instead of asking in the browser, only while no vault is configured and if the folder is writable. |\n| `MEMORA_ADMIN_USER` | `admin` | `server_config` or env | Name of the owner created at startup when no owner exists (needs `MEMORA_ADMIN_PASSWORD`). |\n| `RUST_LOG` | `info` | `server_config` or env | Log filter, for example `info` or `memora=debug`. |\n\n`server_config` accepts only these ten keys. Values are trimmed and validated\n(numbers in range, `true`/`false`, a valid user name, no control characters, at\nmost 2048 bytes).\n\n## Environment only\n\n| Name | Default | What it does |\n|---|---|---|\n| `MEMORA_ADMIN_PASSWORD`, `MEMORA_ADMIN_PASSWORD_FILE` | unset | Creates the owner at startup when none exists (at least 10 characters). Only the argon2id hash is stored; an existing owner is never replaced. |\n| `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE` | unset | Installs an agent API key with id `k_env` and scopes `mcp`, `read`, `write` (at least 24 characters). Only its SHA-256 is stored; the key is replaced when the value changes. |\n| `MEMORA_STATE` | `state` (relative to the working directory) | State directory holding `memora.db`. Created with mode 0700 if missing. |\n| `MEMORA_ASSETS` | the `crates/http/assets` folder of the build tree | Directory of the web UI assets. |\n| `MEMORA_SETUP_HINT` | `memora-cli setup (run on the server)` | Hint returned by `GET /api/auth/state` and shown on the login screen. |\n| `MEMORA_UPDATE_CHECK` | `true` | Release check: shortly after start and then every 6 hours the server asks GitHub (`api.github.com/repos/Codrihub/memora/releases/latest`) for the newest release and the web UI shows when an update is available. `false` (also `0`, `no`, `off`) turns it off; no network call is made. |\n\nThe two secrets can never be stored in `server_config` (the schema rejects\nthem). The `_FILE` variants read the value from a file, for example a Docker\nsecret; a non-empty file wins over the plain variable.\n\nIn `/config`, `MEMORA_API_KEY` offers to create an API key directly, and\n`MEMORA_ADMIN_PASSWORD` points to `/setup` or `/reset`.\n\n## Instance settings (web UI)\n\nThe `settings` table holds one row, edited from the Settings page of the web UI:\n\n| Key | Default | Range | What it does |\n|---|---|---|---|\n| `realm` | `Memora` | 1-64 characters | Instance name shown in the UI and reported by `/api/config` and `/api/auth/state`. |\n| `session_ttl` | `10800` (3 hours) | 300-2592000 seconds | Idle timeout of a browser session. |\n| `session_max_age` | `0` | `0` or at least `session_ttl` | Absolute session lifetime in seconds. `0` means no cap. |\n| `min_password_len` | `10` | 10-256 | Minimum owner password length. |\n| `log_max_mb` | `8` | 1-512 | Size limit in MB of the vault event log (`.events.jsonl`). |\n| `log_max_days` | `0` | 0-3650 | Age limit in days of the vault event log. `0` means no age limit. |\n| `vault_path` | unset | absolute path | The vault folder. Set in the browser after the first sign-in, or with `memora-cli vault PATH`. |\n\n## memora-cli options\n\n| Option | Default | What it does |\n|---|---|---|\n| `--state <DIR>` | `$MEMORA_STATE`, else the state directory of the running `memora` server, else `./state` | State directory to work on. |\n| `--minutes <N>` | `5` | Window length for `setup` and `reset-password`, 1-60. |\n| `--ttl <SECONDS>` | | Window length in seconds (at most 3600). `--minutes` wins when both are given. |\n| `--create` | | With `vault PATH`: create the folder if it does not exist. |\n\nRun as root, `memora-cli` does all database work as the owner of the state\ndirectory, so no root-owned `memora.db*` files appear. See\n[INSTALL.md](INSTALL.md) and [DEPLOYMENT.md](DEPLOYMENT.md) for the commands.\n\n## Docker Compose (`.env`)\n\nThese variables are read by `docker-compose.yml`, not by Memora itself:\n\n| Name | Default | What it does |\n|---|---|---|\n| `COMPOSE_PROJECT_NAME` | `memora` | Compose project name, also the container name prefix. |\n| `IMAGE` | `ghcr.io/codrihub/memora:<version>` | Image to run or build. The compose file pins the release it ships with. |\n| `MEMORA_HTTP_PORT` | `8400` | Host port mapped to the container's port 8400. Use `127.0.0.1:8400` to publish on loopback only. |\n| `MEMORA_DATA_DIR` | `./data` | Host path mounted at `/data` (the vault). |\n| `MEMORA_STATE_DIR` | `./state` | Host path mounted at `/state` (the state directory). |\n| `MEMORA_UID`, `MEMORA_GID` | `1000` | uid:gid the container runs as. Must own both host directories. |\n| `MEMORA_ARM_TTL` | `300` | Passed to the container unchanged. |\n\nCompose also passes these through from `.env` to the container:\n`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`,\n`MEMORA_VAULT_AUTO`, `MEMORA_ADMIN_USER`, `MEMORA_ADMIN_PASSWORD`,\n`MEMORA_ADMIN_PASSWORD_FILE`, `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE`,\n`MEMORA_SETUP_HINT`, `MEMORA_UPDATE_CHECK`, and `RUST_LOG`.\n\nInside the container the image sets `MEMORA_VAULT=/data`,\n`MEMORA_STATE=/state`, `MEMORA_PORT=8400`, `MEMORA_BIND=0.0.0.0`,\n`MEMORA_ARM_TTL=300`, `MEMORA_ASSETS=/app/assets`, and `RUST_LOG=info`.\n\n## State directory\n\n| Path | Content |\n|---|---|\n| `memora.db` (+ `-wal`, `-shm`) | The state database: owner, API keys (hashes), tool switches and per-key permissions, OAuth clients and grants, privacy rules, sessions (hashed ids), setup window and lock state, access rules, settings, `server_config`, activity log. Mode 0600, WAL mode, must be on a local filesystem. See [DATABASE.md](DATABASE.md). |\n| `key-seal.bin` | 32-byte master key (mode 0600) that encrypts the copies of dashboard-created API keys, so the owner can show a key again. Created on first use. Back it up together with `memora.db`. |\n| `backups/` | `memora-cli db backup` output (newest 10 kept by default). |\n| `legacy-json-<unix time>/` | JSON state files found at startup, moved here after their one-time import into `memora.db`. |\n| `internal.token` | Created by the Docker entrypoint. Not used by Memora. |\n\n## Vault files\n\nThe vault holds the markdown notes plus derived and metadata files. See\n[ARCHITECTURE.md](ARCHITECTURE.md#vault-markdown-portable) for the full list.\nThe important ones for operations are `.git/` (history), `.fts.db`\n(rebuildable search index), `.events.jsonl` (event log), and `.Trash/`\n(soft-deleted notes).\n",DN='# MCP\n\nMemora exposes the vault to agents through the Model Context Protocol. The\nserver speaks JSON-RPC 2.0 over the Streamable HTTP transport at `/mcp`, on the\nsame port as the HTTP API and the web UI. There is one MCP endpoint and one tool\ncatalog.\n\n| | |\n|---|---|\n| Endpoint | `POST /mcp` |\n| Protocol versions | `2025-06-18` (preferred), `2025-03-26`, `2024-11-05` |\n| Auth | API key in `Authorization: Bearer <key>` or `X-API-Key: <key>`, or an OAuth 2.1 access token |\n| Discovery card | `GET /.well-known/mcp.json` (public) |\n| Readable catalog | `GET /tools` (HTML page, public) |\n| Catalog size | 74 tools, plus 5 admin tools for keys with the `admin` scope |\n\n`initialize` answers with the protocol version the client asks for when it is\none of the three above, and with `2025-06-18` otherwise.\n\n## Transport\n\n- Requests are JSON-RPC 2.0 objects sent with `POST /mcp`. Batches (JSON\n arrays) are not supported.\n- Responses are plain JSON (`application/json`). The server does not open SSE\n streams and does not issue an `Mcp-Session-Id`.\n- `GET` and `DELETE` on `/mcp` return `405 Method Not Allowed` with\n `Allow: POST`.\n- A notification (a `notifications/*` method without an `id`) gets\n `202 Accepted` and no body.\n- `/mcp` needs a configured vault. Until one is chosen it returns\n `409 {"error":"vault not configured","needs_vault":true}`.\n- A browser session (cookie) may also call `/mcp`. It then needs a same-origin\n request, like the rest of the JSON API.\n\nThe server speaks Streamable HTTP only. A client that can only launch local stdio\nservers can use a bridge such as `mcp-remote` (see below).\n\n## Connecting an agent\n\n### With an API key\n\nCreate a key in the web UI (Keys page), with `memora-cli` (`/keys`), or with\n`POST /api/keys`. The raw key (`memora_live_...`) is shown once. By default a key gets\nthe scopes `mcp`, `read` and `write` and may call every tool. See\n[Tool switches and per-key permissions](contracts/tools-permissions.md) to\nnarrow it.\n\nUse `http://localhost:8400/mcp` for a local install, or your public URL such as\n`https://memory.example.com/mcp` behind a reverse proxy. When the server sets\n`MEMORA_DOMAIN` or `MEMORA_BASE_URL`, requests for any other host get `404`, so\nuse that domain.\n\nClaude Code:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp \\\n --header "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n```\n\nCursor, Windsurf and other clients with an `mcpServers` JSON config (VS Code\nuses the key `servers` in `.vscode/mcp.json`):\n\n```json\n{\n "mcpServers": {\n "memora": {\n "type": "http",\n "url": "http://localhost:8400/mcp",\n "headers": {\n "Authorization": "Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n }\n }\n }\n}\n```\n\nCodex (`~/.codex/config.toml`), with the key in the `MEMORA_API_KEY`\nenvironment variable:\n\n```toml\n[mcp_servers.memora]\nurl = "https://memory.example.com/mcp"\nbearer_token_env_var = "MEMORA_API_KEY"\n```\n\nClients that only run local stdio servers, such as the Claude Desktop config\nfile, can bridge with `mcp-remote` (needs Node.js):\n\n```json\n{\n "mcpServers": {\n "memora": {\n "command": "npx",\n "args": [\n "-y", "mcp-remote", "https://memory.example.com/mcp",\n "--header", "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n ]\n }\n }\n}\n```\n\nSome clients send the key as `X-API-Key: <key>` instead. Both headers are\naccepted.\n\n### With OAuth\n\nClients that support MCP authorization (for example Claude and ChatGPT custom\nconnectors, or Claude Code without a `--header`) can connect with only the URL:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp\n```\n\nThe flow:\n\n1. The client calls `/mcp` without credentials and gets `401` with\n `WWW-Authenticate: Bearer resource_metadata="https://memory.example.com/.well-known/oauth-protected-resource"`.\n2. It reads the protected resource metadata (RFC 9728) and the authorization\n server metadata at `/.well-known/oauth-authorization-server` (RFC 8414; also\n served at `/.well-known/openid-configuration` and under a `/mcp` suffix).\n3. It registers itself with dynamic client registration at\n `POST /oauth/register` (RFC 7591), or uses an HTTPS client metadata document\n URL as its `client_id`. The owner can also register clients in the web UI.\n Redirect URIs must be HTTPS, or plain HTTP on `localhost`, `127.0.0.1` or\n `[::1]`.\n4. It opens `/oauth/authorize` (authorization code with PKCE `S256` only). The\n browser lands on the Memora sign-in page, and the signed-in owner approves or\n denies the connection on a consent card. Codes are valid for 10 minutes.\n5. It exchanges the code at `POST /oauth/token` and receives an access token and\n a refresh token. The only OAuth scope is `mcp`.\n\nThe access token is a regular Memora API key named after the client. It starts\nwith the default scopes (`mcp`, `read`, `write`) and every tool, and it shows up\non the Keys page like any other key, so you can restrict, disable or delete it\nthere. The access token has no expiry. A `refresh_token` grant replaces it with\na fresh one (the old token stops working at once) and rotates the refresh token.\nDisabling or deleting the key ends the connection.\n\nSet `MEMORA_BASE_URL` (for example `https://memory.example.com`) when the server\nruns behind a proxy, so the issuer and endpoint URLs in the metadata are the\npublic ones. Without it the server derives them from the request headers.\n\n### Test from a shell\n\n```bash\ncurl -s -X POST http://localhost:8400/mcp \\\n -H "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY" \\\n -H "Content-Type: application/json" \\\n -d \'{"jsonrpc":"2.0","id":1,"method":"tools/list"}\'\n```\n\n## Discovery card\n\n`GET /.well-known/mcp.json` needs no auth and returns:\n\n| Field | Value |\n|---|---|\n| `name` | `memora` |\n| `version` | The server version |\n| `description` | One-line description of the server |\n| `mcp` | `{endpoint: "/mcp", transports: ["streamable-http"], protocolVersion: "2025-06-18"}` |\n| `auth` | `{type: "api-key", headers: ["Authorization: Bearer <key>", "X-API-Key: <key>"], oauth: "/.well-known/oauth-authorization-server"}` |\n| `capabilities` | `{tools: true, resources: true, prompts: false}` |\n| `tools` | Every catalog tool as `{name, category, description, enabled}`. `enabled` is `false` for tools switched off on this server. Admin tools are not listed. |\n| `resources` | `[{uri, name}]` for the three resources below |\n\nThe card is the same for every caller. To see what a given key may call, use\n`tools/list` with that key.\n\n## Methods\n\n| Method | Purpose |\n|---|---|\n| `initialize` | Handshake. Returns `protocolVersion`, `serverInfo` (`{name, version}`) and `capabilities` (`tools` and `resources`, both with `listChanged: false`). |\n| `notifications/initialized` | Client notification. Without an `id` it gets `202 Accepted`. |\n| `tools/list` | The tools the caller may use, each with `name`, `description` (what it does and when to use it), `inputSchema`, and `_meta.category`. |\n| `tools/call` | Runs one tool. Params are `{name, arguments}`. |\n| `resources/list` | Lists the three resources below. |\n| `resources/read` | Reads one resource. Params are `{uri}`. |\n\nThere are no prompts, no pagination cursors and no change notifications.\n\n### Resources\n\n| URI | Content |\n|---|---|\n| `memory://catalog` | Every catalog tool with `name`, `category`, `description`, `when`, and `inputSchema` (JSON) |\n| `memory://schema` | Data shapes for a note, a folder, the graph, and activity (JSON) |\n| `memory://guide` | A short guide for agents using the vault (Markdown) |\n\n`resources/read` returns `{contents: [{uri, mimeType, text}]}`.\n\n## Results and errors\n\nA successful tool call returns the tool\'s JSON result as text:\n\n```json\n{\n "jsonrpc": "2.0",\n "id": 2,\n "result": {\n "content": [{ "type": "text", "text": "{...}" }],\n "isError": false\n }\n}\n```\n\nA tool that fails (bad arguments, note not found, unknown tool name) returns the\nsame envelope with `isError: true` and the error message as the text. The HTTP\nstatus stays `200`.\n\nJSON-RPC errors:\n\n| Code | When |\n|---|---|\n| `-32700` | The body is not valid JSON (HTTP `400`). |\n| `-32600` | The body is not a JSON-RPC request object (HTTP `400`). |\n| `-32601` | Unknown method: `unsupported method: <method>`. |\n| `-32602` | `resources/read` with an unknown URI: `unknown resource: <uri>`. |\n| `-32003` | The tool exists but the caller may not use it. Messages: `tool not allowed for this API key: <name>`, `tool disabled on this server: <name>`, `API key lacks the \'write\' scope for tool: <name>`. |\n\nHTTP errors before JSON-RPC runs:\n\n| Status | When |\n|---|---|\n| `401` | No key, or a key that is unknown, disabled, deleted or replaced by a roll (`invalid API key`). Carries a `WWW-Authenticate` header that points OAuth clients at the protected resource metadata. |\n| `403` | The key lacks the `mcp` scope (`{"error":"API key lacks the \'mcp\' scope","required_scope":"mcp"}`), or a browser request failed the same-origin check. |\n| `405` | Any method other than `POST`. |\n| `409` | No vault is configured yet. |\n| `429` | Rate limit or cooldown after failed attempts. |\n\n## What each key sees\n\n`tools/list` is filtered per caller:\n\n- A tool switched off on the server is hidden for everyone.\n- A key whose tool list is not `"*"` only sees the tools in its list.\n- A key without the `write` scope only sees read-only tools.\n- Admin tools are added for keys with the `admin` scope (and for browser\n sessions).\n\n`tools/call` on a tool that `tools/list` would hide returns `-32003`. Details\nare in [Tool switches and per-key permissions](contracts/tools-permissions.md).\n\n### Privacy rules\n\nThe owner can hide notes and folders from specific agents (web UI,\n`/api/privacy`, or the `privacy_*` admin tools). For an API key covered by a\nrule, every tool works as if the hidden paths did not exist: they are left out\nof listings, search, the graph, tags, events, logs, locks and folder metadata; a\nhidden path named in an argument is answered as not found, for reads and writes\nalike; and folder operations that would carry hidden items along are refused.\nIf the rules cannot be read, the key sees nothing (fail closed). Browser\nsessions are never filtered.\n\n## Tools\n\nR = read-only (needs only the `mcp` scope). W = changes the vault or server\nstate (also needs the `write` scope). Unless marked required, arguments are\noptional. Paths are vault-relative, for example `Projects/Plan.md`.\n\n### Notes (`note`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_memory` | R | none | Every note grouped by folder: `{folder: [{path, name, folder, mtime}]}`. |\n| `read_memory` | R | `path` (string, required) | Markdown body, frontmatter, tags and backlinks of one note. |\n| `create_memory` | W | `title` (string, required), `folder` (string, default `Memory`; `Root` or empty for the top level), `content` (string; default is a stub with `created` frontmatter and a heading) | Creates `<folder>/<title>.md` and returns `{ok, path}`. |\n| `save_memory` | W | `path` (string, required), `content` (string, required) | Replaces the whole note. |\n| `patch_memory` | W | `path` (string, required), `ops` (array, required) | Partial edits. Each op is an object: `{op:"append", text}`, `{op:"prepend", text}`, `{op:"replace", find, with}`, `{op:"set_field", field, value}`, `{op:"add_tag", tag}`, `{op:"remove_tag", tag}`. |\n| `delete_memory` | W | `path` (string, required) | Deletes a note (recoverable from git history). |\n| `move_memory` | W | `path` (string, required), `folder` (string, required) | Moves a note into another folder. Wikilinks resolve by note name, so they keep working. |\n| `rename_memory` | W | `path` (string, required), `new_name` (string, required) | Renames a note in its folder. |\n\n### Search (`search`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_stats` | R | none | Counts of notes, links and folders. |\n| `search_memory` | R | `q` (string, required; `query` is accepted as an alias), `limit` (integer, default 12) | Search titles and bodies. Supports `tag:x` and `#x`. |\n\n### Query (`query`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `query_memory` | R | `folder`, `tags`, `author`, `type`, `status` (strings), `limit` (integer, default 50) | Filter notes by frontmatter. |\n| `find_similar` | R | `path` (string, required), `limit` (integer, default 8) | Notes most similar to one note (shared tags and words). |\n| `suggest_links` | R | `path` (string, required), `limit` (integer, default 8) | Similar notes not yet linked from this one. |\n| `list_tags` | R | none | Every tag with its usage count. |\n| `rename_tag` | W | `old` (string, required), `new` (string, required) | Renames a tag across the vault. |\n| `merge_tag` | W | `a` (string, required), `b` (string, required) | Merges tag `a` into tag `b` across every note. |\n\n### Tags (`tag`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_tags` | R | `path` (string; not in the advertised schema) | Every tag with its count, or the tags of one note when `path` is given. |\n| `search_by_tag` | R | `tag` (string, required), `limit` (integer, default 50; not in the advertised schema) | Every note carrying a tag. |\n| `add_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Adds tags to a note. A leading `#` is stripped. |\n| `remove_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Removes tags from a note. |\n| `set_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Replaces a note\'s tag list. |\n\n### Folders (`folder`, `ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_folders` | R | none | `{count, folders: [{name, count, color}]}`. |\n| `create_folder` | W | `name` (string, required) | Creates a folder. |\n| `rename_folder` | W | `folder` (string, required), `name` (string, required, one segment) | Renames a folder in place. Notes, sub folders, color and icon move along. |\n| `move_folder` | W | `folder` (string, required), `into` (string; empty or `Root` = top level) | Moves a folder with everything in it. |\n| `move_folder_contents` | W | `folder` (string, required), `into` (string; empty = top level) | Moves everything inside a folder into another folder, then removes the empty folder. Name clashes get a `-N` suffix. |\n| `delete_folder` | W | `folder` (string, required) | Deletes a folder. Its notes move to Root. |\n| `folder_stats` | R | `folder` (string, required) | Note count and metadata for one folder. |\n| `get_folder_meta` | R | `folder` (string) | Color, icon and description of one folder, or of every folder. |\n| `set_folder_meta` | W | `folder` (string, required), `color`, `icon`, `desc` (strings) | Sets folder display metadata. A field sent as an empty string is cleared. |\n\n### Graph (`graph`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_graph` | R | none | Whole graph: `{nodes: [{id, path, folder, color, degree, tags, mtime}], links: [{source, target}]}`. |\n| `get_neighbors` | R | `path` (string, required), `depth` (integer, default 1) | Notes within N hops. |\n| `get_subgraph` | R | `path` (string, required), `depth` (integer, default 1), `max_nodes` (integer, default 60) | Subgraph around one note. |\n| `find_path` | R | `source` (string, required), `target` (string, required) | Shortest wikilink path between two notes. |\n| `get_hubs` | R | `limit` (integer, default 10) | Most connected notes. |\n| `get_isolated` | R | none | Notes with no links in or out. |\n| `link_stats` | R | `path` (string, required) | Outgoing, incoming and unresolved links of one note. |\n| `broken_links` | R | none | Wikilinks pointing at notes that do not exist. |\n\n### Versioning (`version`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_history` | R | `path` (string, required), `limit` (integer, default 20) | Git history of a note. A single entry is returned as an object, several as an array. |\n| `get_note_at` | R | `path` (string, required), `rev` (string, required) | `{ok, path, rev, content}` at a revision. |\n| `diff` | R | `path` (string, required), `rev_a` (string, required), `rev_b` (string) | Diff between two revisions, or `rev_a` against the working tree. |\n| `restore_memory` | W | `path` (string, required), `rev` (string, required) | Restores a note to a revision. |\n| `snapshot` | W | `label` (string, required) | Tags the whole vault (git tag). |\n| `soft_delete` | W | `path` (string, required) | Moves a note to `.Trash`. |\n| `restore_trash` | W | `name` (string, required), `into` (string, default `Root`) | Restores a note from `.Trash` into a folder. |\n\n### Bulk writes (`write`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `batch_create` | W | `notes` (array, required) of `{title, folder (default Root), content}` | Creates many notes in one call. |\n| `duplicate_memory` | W | `path` (string, required) | Copies a note as `<name>-copy` in the same folder. |\n| `merge_memory` | W | `paths` (array of strings, required), `into` (string, required) | Merges several notes into one target note. |\n| `template_create` | W | `template` (string, required), `title` (string, required), `folder` (string, default `Root`), `variables` (object) | Creates a note from a file in `Templates/` with `{{var}}` substitution. |\n| `bulk_replace` | W | `find` (string, required), `replace` (string, required), `folder` (string), `regex` (boolean, default false), `dry_run` (boolean, default false) | Find and replace across notes. Needs `write` even with `dry_run`. |\n| `bulk_delete` | W | `paths` (array of strings), `folder` (string) | Deletes many notes by list or by folder. |\n\n### Collaboration (`collab`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `lock_node` | W | `path` (string, required), `owner` (string, default the caller), `ttl` (integer seconds, default 300) | Soft lock on a note. |\n| `release_lock` | W | `path` (string, required), `owner` (string, default the caller) | Releases a lock. |\n| `get_locks` | R | none | Active locks. |\n| `mention_agent` | W | `agent` (string, required), `path` (string, required), `message` (string) | Writes `> @agent: message` into a note. |\n| `get_assignments` | R | `agent` (string) | Notes with `assigned_to` in their frontmatter. |\n\n### Activity and health (`ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_events` | R | `since` (number, unix time), `folder`, `actor` (strings), `limit` (integer, default 50) | Recent note created, updated and deleted events. |\n| `presence` | R | `window` (integer seconds, default 300) | Agents active within the window. |\n| `get_logs` | R | `range` (string, default `1d`; also `7d`, `today`, `yesterday`), `actor` (string), `limit` (integer, default 100) | Activity log for a period. |\n| `search_logs` | R | `q` (string, required), `range` (string, default `7d`), `actor` (string), `limit` (integer, default 100) | Keyword search in the activity log. |\n| `digest` | R | `folder` (string), `since` (number) | Event counts per actor and per type. |\n| `healthcheck` | R | none | Note count, broken links, orphans and git status. |\n| `stale_detection` | R | `days` (integer, default 30) | Notes untouched for more than N days. |\n\n### Identity (`identity`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `set_my_name` | W | `name` (string, required) | Sets the display alias shown in the activity feed and log. |\n| `set_my_color` | W | `color` (string, required; `#rrggbb`, or `""` to reset) | Sets the calling API key\'s display color. Fails for browser sessions. |\n| `list_actors` | R | none | `{me, aliases}`: the caller and every known alias. |\n\n### Import and export (`interop`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `export_memory` | W | `paths` (array of strings, required; notes or folders), `out_path` (string) | Writes a zip of the given paths to the server\'s exchange folder and returns `{ok, path, name, bytes}`, where `path` and `name` are the zip\'s file name. `out_path` is a plain file name ending in `.zip` (letters, digits, `.`, `_`, `-`, at most 120 characters); the default is `memora-export-<time>.zip`. |\n| `import_memory` | W | `zip_path` (string, required), `overwrite` (boolean, default false) | Imports notes from a zip in the exchange folder, by the file name `export_memory` returned. |\n\nThe exchange folder is `memora-exchange` in the server\'s temporary directory.\nTools never read or write anywhere else on the server\'s disk.\n\n### Checks, to-dos and pins (`ux`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_todos` | R | `path` (string) | Open checklist items (`- [ ]`) in one note or the whole vault. |\n| `follow_ups` | R | none | Notes whose status is still awaiting action. |\n| `validate_memory` | R | `path` (string, required) | Checks frontmatter, created date, tags and links of a note. |\n| `list_pins` | R | none | The owner\'s pinned notes and folders in sidebar order: `{count, pins:[{kind, path, position, missing}]}`. `missing` is true when the path no longer exists (renamed or deleted outside Memora). |\n| `pin` | W | `path` (string, required), `kind` (`note` or `folder`; default: what the path is on disk), `position` (integer from 0; default: the end) | Pins an existing note or folder, or moves its pin. A note path may leave out `.md`. At most 200 pins. Returns the list. |\n| `unpin` | W | `path` (string, required), `kind` | Removes a pin; the note or folder is not touched. Returns the list with `removed`. |\n\nPins are shared by every browser of the owner (`/api/pins`). They follow their note or\nfolder through renames and moves done by Memora (over MCP or HTTP, including notes inside\na moved folder) and are removed when the item is deleted or moved to the trash; deleting a\nfolder removes every pin under it. A key whose privacy rules hide a path neither lists\nnor changes its pin, and `position` counts only the pins the key can see.\n\n### Admin tools (`admin`)\n\nListed and callable only for keys with the `admin` scope (and for browser\nsessions). They are not part of the switchable catalog: global tool switches and\na key\'s tool list do not apply to them, and they do not need `write`.\n\n| Tool | Arguments | Purpose |\n|---|---|---|\n| `admin_list_tools` | none | `{tools: [{name, category, description, enabled}]}` for every catalog tool. |\n| `admin_set_tool` | `name` (string, required), `enabled` (boolean, required) | Switches a catalog tool on or off for every key. Returns `{ok, name, enabled}`. |\n| `privacy_list` | `path` (string), `kind` (`node` or `folder`) | Without `path`: every privacy rule. With `path`: that note or folder\'s own rule, the folder rules it inherits, and which agents can see it. |\n| `privacy_set` | `path` (string, required), `agents` (array of key ids or names, required; a comma-separated string also works), `kind` (`node` or `folder`), `mode` (`deny` or `allow_only`, default `deny`) | Replaces the rule on a path. `deny` hides it from the listed agents; `allow_only` hides it from every other agent, including keys created later. `deny` with no agents removes the rule. A node rule follows its note through renames and moves. |\n| `privacy_clear` | `path` (string, required), `kind` (`node` or `folder`) | Removes the path\'s own rule. Rules on parent folders still apply. |\n\nWhen `kind` is omitted it is taken from the path on disk: a folder if a folder\nexists there, otherwise a note.\n\n## Identity and tracking\n\nEvery tool call is published to the web UI\'s realtime activity stream as an\n`ai_activity` start and end pair, named after the API key (or the signed-in\nuser), with the note paths involved. Calls are also counted per key: the Keys\npage and `GET /api/keys` show each key\'s `uses`, `last_ip`, and the tools it has\ncalled recently. `initialize` registers the connection under the key\'s name\n(`GET /api/aliases`). `set_my_name` changes the alias shown in the activity\nfeed and log, and `set_my_color` changes the key\'s color in the UI. See\n[API.md](API.md) for the HTTP endpoints.\n',zN='# HTTP API\n\nThe `memora` binary serves the HTTP API, the MCP endpoint, the OAuth endpoints,\nthe web UI, and the WebSocket on one port. This document lists the HTTP endpoints.\n\n## Authentication\n\nThe Auth column in the tables below uses these levels:\n\n- None: reachable without credentials.\n- Session: requires the `memora_sess` cookie set by a successful login.\n- Key (`scope`): an API key sent as `Authorization: Bearer <key>` or `X-API-Key: <key>`\n that carries the named scope.\n- Session or key (`scope`): either of the above.\n- Session only: an API key is not enough. API keys get `401` (or `403` where noted).\n- +CSRF: the same-origin check described below applies.\n\n### API key scopes\n\nA key carries any of the scopes `mcp`, `read`, `write`, and `admin`. New keys get\n`mcp`, `read`, and `write` unless other scopes are requested. The scope a route\nneeds is decided by its path and method:\n\n| Scope | Routes |\n|---|---|\n| `mcp` | `/mcp` |\n| `admin` | `/api/tools`, `/api/keys` and `/api/keys/*`, `/api/access` and `/api/access/*`, `/api/logs/settings`, `/api/oauth/clients` and `/api/oauth/clients/*`, `/api/privacy` and `/api/privacy/*` |\n| `read` | Every other `GET` or `HEAD` under `/api/` |\n| `write` | Every other method under `/api/` |\n\nA key without the needed scope gets `403 {error, required_scope}`. A missing key\ngets `401`; for `/mcp` the `401` carries a `WWW-Authenticate` header,\n`Bearer resource_metadata="<base>/.well-known/oauth-protected-resource"`, so OAuth\ncapable clients can start sign-in. An invalid key gets `401` and is logged; an\nIP that keeps presenting invalid keys is put on a cooldown (`429`).\n\n`/api/auth/*` never accepts an API key: without a valid session it answers `401`.\n\nAPI keys see the vault through their privacy rules (see [Privacy](#privacy)):\nnotes and folders hidden from a key behave as if they do not exist. A browser\nsession sees everything.\n\n### CSRF\n\nWrite endpoints that accept a session check the request origin whenever a\nsession cookie is present: `Origin` (or, without it, `Referer`) must match the\nrequest `Host` (or an `X-Forwarded-Host` sent by a trusted proxy), and\n`Sec-Fetch-Site: cross-site` is refused. A failed check is\n`403 {"error":"origin mismatch"}`. Requests without a session cookie (API-key\nclients) pass, since a browser cannot attach an API key on its own.\n\nThe public auth forms (`/api/auth/login`, `/api/auth/verify`,\n`/api/auth/bootstrap`, `/api/auth/reset`) also refuse a foreign or `null`\n`Origin` when no cookie exists yet. A request with neither `Origin` nor\n`Referer` (curl, the CLI) passes.\n\n### Locked instance\n\nWhile the instance is LOCKED, `/api/*` and `/mcp` answer\n`423 {error, locked: true, hint}` except for `/api/auth/state`, `/api/auth/verify`,\n`/api/auth/login`, `/api/auth/logout`, `/api/auth/bootstrap`, and\n`/api/auth/reset`. Other pages redirect to `/login?locked=1`; static assets,\n`/login`, `/logout`, `/healthz`, and `/favicon.ico` are still served.\n`/api/auth/login` itself answers `423` while locked.\n\n### Vault not configured\n\nUntil a vault folder is configured, `/mcp` and every `/api/*` route except\n`/api/auth/*`, `/api/settings*`, `/api/config`, `/api/keys*`, `/api/tools`,\n`/api/access*`, and `/api/ui/*` answer\n`409 {"error":"vault not configured", "needs_vault":true}`.\n\n### Limits and other gates\n\n- Requests for a host outside the configured domain list get a bare `404`.\n- Access rules (see `/api/access`) can block a caller:\n `403 {"error":"access denied by stack rule", ip}`.\n- Per-IP rate limits answer `429` with a `Retry-After` header and\n `{error, limited, cooldown, retry_after}`. Login, code check, setup, reset, profile,\n password, and username changes have a stricter limit and a cooldown after\n repeated failed attempts. Requests from the machine itself and `/healthz` are\n not limited.\n- A request that takes longer than 30 seconds is answered with `408`.\n- A password hashing pool that is busy answers `503` with `Retry-After: 2`.\n\nResponses are JSON unless stated otherwise. Errors are `{"error": "..."}`. Vault\nerrors map to `404` for not-found (including paths hidden from the caller) and\n`400` for bad input.\n\n## Health and discovery\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/healthz` | None | `{ok, server}` for unauthenticated callers from other machines. A signed-in browser or a caller on the same machine gets `{ok, server, version, vault_configured, vault, armed, locked, base_url, base_url_configured}`. |\n| GET | `/.well-known/mcp.json` | None | The MCP discovery card: `{name, version, description, mcp, auth, capabilities, tools, resources}`. `tools` lists the full catalog with `enabled` per tool. |\n| GET | `/tools` | None | An HTML rendering of the tool catalog. A signed-in browser gets the app shell instead. |\n| POST | `/mcp` | Key (`mcp`), or Session (+CSRF) | MCP over streamable HTTP (JSON-RPC in, JSON-RPC out). See [MCP.md](MCP.md). A session has full access; a key is limited by its tool grant. Notifications get `202` with no body. Malformed JSON is `400` with a JSON-RPC error. Other methods get `405` with `Allow: POST`. |\n\n## Auth\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/auth/state` | None | `{bootstrap, realm, min_password_len, gateway, armed, locked, setup_hint, ready, checks:{vault, state}, code_required, cooldown, vault_configured}`. Adds `signed_out` (`password_changed` or `signed_out_remotely`) when the browser\'s session was ended on purpose, and `mode`, `expires_in`, `ttl` while a setup or reset window is open. |\n| POST | `/api/auth/verify` | None (+CSRF) | Checks the setup code shown on the server before the setup or reset form is shown. Body: `{code}`. Returns `{ok, mode, expires_in, user}`. `403` when no window is open or the instance is not ready. A wrong code closes the window and voids the code: `403 {error, burned:true}`. |\n| POST | `/api/auth/login` | None (+CSRF) | `{ok, user, expires_in, redirect}` and sets the session cookie. Body: `{username, password}`. `400` when a field is missing, `401` on bad credentials, `403` if the account is disabled, `423` if locked, `429` during a cooldown. |\n| POST | `/api/auth/logout` | None (+CSRF) | `{ok:true}`. Ends the session named by the cookie, if any, and clears the cookie. |\n| POST | `/api/auth/bootstrap` | None (+CSRF) | Creates the owner account. Body: `{code, username, password}`. Returns `{ok, user, redirect, persisted}` and sets a session cookie. The username is stored lowercase. `400` for an invalid username or password length; `403` unless a window is open, the code is right, the instance is ready, and no account exists. |\n| POST | `/api/auth/reset` | None (+CSRF) | Sets a new password for the single account, and may rename it. Body: `{code, username, password}`. Returns `{ok, user, persisted}`. Signs out every session. `400` for invalid input; `403` unless a window is open, the code is right, and an account exists. |\n| POST | `/api/auth/profile` | Session only (+CSRF) | With `password` in the body, changes the password exactly like `POST /api/settings/password` (body `{current, password, confirm}`). Otherwise sets `display_name` (at most 48 characters) and returns `{ok, changed, persisted, user, password_changed:false}`; with no `display_name` it returns `{ok, changed:false}`. |\n| GET | `/api/auth/me` | Session only | `{authenticated, user, enabled, expires_in}`. `401` without a session. |\n| GET | `/api/auth/events` | Session only | Recent entries of the security activity log, newest first: `{events:[{at, event, ip, user, detail, actor, actor_kind, actor_id}], count}`. `user` is the stored actor (`key:<id>` for API-key calls); `actor` is the display name (the key\'s current name, falling back to its id; the username for the browser), `actor_kind` is `agent` or `user` (null when there is no actor). Query: `limit` (default 200, max 2000), `q`. |\n\n## Pages\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/login` | None | The sign-in page. A signed-in browser is redirected to `/` unless the instance is locked or the query has `oauth` (the OAuth consent card). |\n| any | `/logout` | None | Ends the session, clears the cookie, and redirects to `/login`. A cross-site request only clears the cookie. |\n| GET | `/`, `/index.html` | Session | The web app shell. Without a session: `302` to `/login`. `503` when the UI assets are not installed. |\n| GET | App routes (see below) | Session | The same app shell as `/`. Without a session: `302` to `/login?r=<path>`, so sign-in returns to the page. |\n\nApp routes are the web app\'s client-side pages: `/brain`, `/nodes`, `/graph`,\n`/canvas`, `/tags`, `/activity`, `/agents`, `/access`, `/settings`,\n`/overview`, `/welcome`, the older names `/home`, `/vault`, `/logs`, `/keys`,\nand `/node/` or `/node/<percent-encoded vault path>`. The path is never used to\nread a file; a path holding NUL or another control character (raw or\npercent-encoded) is `400`. `/tools` is an app route for a signed-in browser and\nthe public tool catalog otherwise.\n\nHTML pages are sent with `Cache-Control: no-cache, no-store, must-revalidate`\nand a per-response CSP nonce.\n\nAny other `GET` that asks for HTML (`Accept: text/html`), is outside `/api/`,\n`/mcp`, `/oauth`, and `/.well-known`, and has no file extension in its last\nsegment gets the app shell (which shows its "page not found" view). Every other\nunmatched request is `404 {"error":"not found"}`.\n\n## Static assets\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/assets/{name}` | None | Static UI assets (whitelisted filenames only, else `404`). |\n| GET | `/app.js`, `/app.css`, `/login.css` | None | The UI bundle and styles. Revalidated on every load (`Cache-Control: no-cache`, ETag). |\n| GET | `/favicon.svg` | None | The icon. |\n| GET | `/favicon.ico` | None | `204` with no body. |\n| GET | `/manifest.webmanifest`, `/sw.js`, `/robots.txt`, `/offline.html`, `/icon-192.png`, `/icon-512.png`, `/icon-maskable-512.png`, `/apple-touch-icon.png` | None | PWA files and `robots.txt`. Images and the manifest are cached for 5 minutes; code is revalidated on every load. |\n\n## Vault\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/tree` | Session or key (`read`) | Notes grouped by folder. |\n| GET | `/api/note` | Session or key (`read`) | `{path, name, content, html, tags, frontmatter, backlinks, size, mtime}`. Query: `path` (`400` when empty). |\n| GET | `/api/vault/file` | Session or key (`read`) | The raw bytes of one image file in the vault (PNG, JPEG, GIF, WebP, AVIF, BMP, ICO; never SVG). Query: `path` (vault-relative). The file content must match its type. At most 10 MiB (`413`). Sent with an `ETag` (`304` on `If-None-Match`), `Cache-Control: private, max-age=300`, and a sandbox CSP. `400` invalid path, `403` path not allowed, `404` not found, `415` not an image. |\n| GET | `/api/folder-meta` | Session or key (`read`) | Folder metadata keyed by folder name. Query: `folder` (optional). |\n| POST | `/api/save` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{path, content}`. Overwrites the note. |\n| POST | `/api/create` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{title, folder?, content?}`. |\n| POST | `/api/rename` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, name}`. |\n| POST | `/api/move` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, folder?}`. |\n| POST | `/api/delete` | Session or key (`write`, +CSRF) | `{ok:true}`. Body: `{path}`. |\n| POST | `/api/folder` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{name}`. |\n| POST | `/api/folder/rename` | Session or key (`write`, +CSRF) | `{ok, from, to, notes}`. Body: `{folder, name}`. |\n| POST | `/api/folder/move` | Session or key (`write`, +CSRF) | Moves a folder and everything in it. `{ok, from, to, notes}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/folder/move-contents` | Session or key (`write`, +CSRF) | Moves everything inside a folder into another one, then removes the emptied folder. Name clashes get a `-N` suffix. `{ok, from, to, moved}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/delete-folder` | Session or key (`write`, +CSRF) | Deletes a folder and moves its notes to the top level. `{ok, deleted_folder, moved_to_root}` where `moved_to_root` lists the new note paths. Body: `{folder}`. |\n| POST | `/api/folder-meta` | Session or key (`write`, +CSRF) | `{ok, folder}`. Body: `{folder, color?, icon?, desc?}`. |\n\nThe three folder operations also publish a `folder_changed` realtime event so\nopen browsers reload their tree.\n\n## Search and graph\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/search` | Session or key (`read`) | `{q, count, hits:[{path, name, folder, score, snippet}]}`, at most 20 hits. Query: `q`. Supports `tag:x` and `#x`. |\n| GET | `/api/stats` | Session or key (`read`) | `{notes, links, folders}`. |\n| GET | `/api/graph` | Session or key (`read`) | `{nodes:[{id, path, folder, color, degree, tags}], links:[{source, target}]}`. `tags` holds inline `#tags` plus frontmatter `tags` (as the note view reports them). Realtime `node_*` events\' `node` payload carries `tags` too. |\n| GET | `/api/aliases` | Session or key (`read`) | `{aliases:[{alias, key_id, key_name, first_seen, last_seen, connections, actor, actor_kind}]}`: one record per API key that sent MCP `initialize`, kept in memory until the server restarts. `key_name` and `actor` are the key\'s current name (fallback: the id). |\n| GET | `/api/actors` | Session or key (`read`) | `{actors:[{actor, alias, display, events, tools, last_ip, last_ts, seen_minutes_ago}], count}`. `seen_minutes_ago` is `-1` when the actor has no events. |\n\n## Privacy\n\nPrivacy rules hide notes or folders from chosen agents (API keys). A rule has a\n`kind` (`node` or `folder`), a `path`, a `mode` (`deny`: hidden from the listed\nkeys; `allow_only`: hidden from every key except the listed ones), and a list\nof keys. Folder rules apply to everything inside the folder.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/privacy` | Session or key (`admin`) | `{count, rules:[{id, kind, path, mode, keys:[{id, name, color}], created_at, updated_at}], agents:[{id, name, color, enabled}]}`. |\n| GET | `/api/privacy/path` | Session or key (`admin`) | The privacy state of one path: `{path, kind, own, own_rules, inherited, agents:[{id, name, color, enabled, can_see, hidden_by}], private}`. `own` is `{mode, keys}` or `null`. Query: `path`, `kind` (optional; defaults to `folder` when the path is a folder on disk, else `node`). |\n| PUT | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Replaces the rule on a path. Body: `{path, kind?, mode, keys}`. `mode` defaults to `deny`; `keys` is a list of key ids (or unique key names). `deny` with no keys removes the rule. Returns the same shape as `GET`. |\n| DELETE | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Removes the rule on a path. Query: `path`, `kind` (optional). Returns the same shape as `GET`. |\n\nChanges are written to the activity log and publish a `privacy_changed`\nrealtime event.\n\n## API keys, tools, and access\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/keys` | Session or key (`admin`) | `{count, keys:[{id, name, enabled, scopes, tools, prefix, created, color, revealable, uses, last_ip, used_tools}]}`. `tools` is `"*"` or a list of tool names; `revealable` says whether the secret can be shown again; `used_tools` lists recently used tools and routes. |\n| POST | `/api/keys` | Session or key (`admin`, +CSRF) | Creates a key. Body: `{name?, tools?, scopes?, color?}`. `tools` is `"*"` or a list of tool names; `scopes` a list of scope names (an empty list means the defaults). Returns `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. `400` for an unknown tool or scope. |\n| POST | `/api/keys/roll` | Session or key (`admin`, +CSRF) | New secret for an existing id. Body: `{id}`. Returns `{ok, id, key, prefix, persisted}`. `404` for an unknown id. |\n| POST | `/api/keys/reveal` | Session only (+CSRF) | Shows the secret of a key created or rolled from the dashboard again. Body: `{id, current}` where `current` is the owner\'s password. Returns `{ok, id, key}`. `403` for a wrong password; `429` after 5 wrong passwords (5 minute pause); `404 {error:"not_stored", message}` when the secret is not stored (for example keys created by the CLI or by OAuth). |\n| POST | `/api/keys/update` | Session or key (`admin`, +CSRF) | Body: `{id, name?, enabled?, tools?, scopes?, color?}`. `color` as `""` or `null` clears it. Returns `{ok, id, name, enabled, color, tools, scopes, persisted}`. `400` for an unknown tool or scope, `404` for an unknown id. |\n| POST | `/api/keys/delete` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Moves the key to the trash. Body: `{id}`. |\n| POST | `/api/keys/restore` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Restores a deleted key. Body: `{id}`. `404` when no deleted key has that id. |\n| GET | `/api/tools` | Session or key (`admin`) | `{tools:[{name, category, description, enabled}]}`: the MCP tool catalog with the global on/off switch of each tool. |\n| POST | `/api/tools` | Session or key (`admin`, +CSRF) | Switches a tool on or off for every caller. Body: `{name, enabled}`. Returns `{ok, name, enabled}`. `400` for an unknown tool. |\n| GET | `/api/access` | Session or key (`admin`) | `{default_allow, rules, count}`. |\n| POST | `/api/access/test` | Session or key (`admin`) | `{action, would_lock_out_caller}` for the given address or domain. Body: `{ip?, domain?}`. |\n| POST | `/api/access/rules` | Session or key (`admin`, +CSRF) | `{ok, count, persisted}`. Body: `{op, kind, value, action}`. `op` is `add` (default) or `remove`. `kind` is `ip`, `range`, `cidr`, `domain`, or `all`; `value` is required unless `kind` is `all`. `action` is `allow` or `block` (default `block`). `remove` deletes every rule matching the given `kind` and `value`; `404` when none match. |\n| GET | `/api/config` | Session or key (`read`) | `{realm, min_password_len, session_ttl, vault, version, gateway, update}`. `update` is the cached release check: `{current, latest, available, url, checked_at, state}`, `state` one of `ok`, `none` (no release published), `error`, `disabled`, `pending`. |\n\n## Settings\n\nAll settings endpoints need a signed-in browser.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/settings` | Session only | `{user, vault_configured, vault, vault_suggested, vault_writable, stats, min_password_len, expires_in, session_ttl, session_max_age, state_dir}`. `stats` is `{notes, links, folders}` or `null` without a vault. |\n| POST | `/api/settings/password` | Session only (+CSRF) | Body: `{current, password, confirm}`. Returns `{ok, user, password_changed, revoked_sessions, persisted}`. Every other session is signed out. `400` for a short, mismatched, or unchanged password; `403` for a wrong current password (counts toward the login cooldown). |\n| POST | `/api/settings/username` | Session only (+CSRF) | Renames the account. Body: `{username, current}`. Returns `{ok, user, changed}` (plus `persisted` when changed). The username is stored lowercase. Sessions stay signed in. `400` for an invalid username, `403` for a wrong password. |\n| POST | `/api/settings/vault` | Session only (+CSRF) | Sets the vault folder and switches the running server to it. Body: `{path, create?}`. `path` must be absolute, without `..`, writable, not a system folder, and not overlap the state folder; with `create` a missing folder is created (its parent must exist). Returns `{ok, vault, created, stats}`. `400` with a message when the folder is refused. |\n| GET | `/api/settings/sessions` | Session only | `{sessions:[{id, current, source, alias, ip, user_agent, created_at, last_seen, expires_in}], count}`: live browser sessions. API keys are not sessions and never appear here. |\n| POST | `/api/settings/sessions/revoke` | Session only (+CSRF) | Signs other browsers out. Body: `{id}` or `{others:true}`. Returns `{ok, revoked}`. `400` for the current session (use logout), `404` when the session has already ended. |\n| POST | `/api/settings/sessions/rename` | Session only (+CSRF) | Names a device. Body: `{id, alias}`; an empty alias clears it. Returns `{ok, alias}`. |\n| GET | `/api/settings/sessions/activity` | Session only | `{events, count, ip, since}`: activity log entries from that session\'s IP address since it signed in, API-key entries left out, newest first, at most 200. Query: `id`. |\n\nSession `id` values are the short ids returned by `GET /api/settings/sessions`\n(a unique prefix also works). An ambiguous or malformed id is `400`.\n\n## OAuth\n\nMemora is an OAuth 2.1 authorization server for remote MCP clients. Only the\nauthorization code flow with PKCE (`S256`) is supported. The access token is a\nnew API key named after the client, with the default scopes (`mcp`, `read`,\n`write`) and every tool; it appears on the Agents page like any other key and\nis revoked by deleting or disabling that key. URLs in the metadata use\n`MEMORA_BASE_URL` when it is set, else the scheme and host of the request.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/.well-known/oauth-protected-resource`, `/.well-known/oauth-protected-resource/mcp` | None | Protected resource metadata (RFC 9728): `{resource, authorization_servers, bearer_methods_supported, scopes_supported, resource_name}`. |\n| GET | `/.well-known/oauth-authorization-server`, `/.well-known/oauth-authorization-server/mcp`, `/.well-known/openid-configuration` | None | Authorization server metadata (RFC 8414): `issuer`, the authorization, token, and registration endpoints, supported response types (`code`), grant types (`authorization_code`, `refresh_token`), PKCE methods (`S256`), token endpoint auth methods, `scopes_supported` (`mcp`), and `client_id_metadata_document_supported: true`. |\n| POST | `/oauth/register` | None | Dynamic client registration (RFC 7591). Body: `{redirect_uris, client_name?}`. `redirect_uris` holds 1 to 10 URIs, each HTTPS or plain HTTP on `localhost`, `127.0.0.1`, or `[::1]`, without a fragment. Returns `201 {client_id, client_name, redirect_uris, client_id_issued_at, token_endpoint_auth_method, grant_types, response_types}`. `400 {error, error_description}` for invalid metadata. |\n| GET | `/oauth/authorize` | None | `302` to `/login?oauth=1&<query>`, where the sign-in page shows a consent card (after sign-in when needed). |\n| POST | `/oauth/token` | None | Form-encoded or JSON body. `grant_type=authorization_code` with `code`, `code_verifier`, `client_id` (or HTTP Basic), and optional `redirect_uri`; or `grant_type=refresh_token` with `refresh_token` and optional `client_id`. Returns `{access_token, token_type:"Bearer", refresh_token, scope:"mcp"}`. Codes are single use and expire after 10 minutes. A refresh gives the same key a new secret and a new refresh token. Errors are `400 {error, error_description}` (`invalid_request`, `invalid_grant`, `unsupported_grant_type`). |\n| GET | `/api/oauth/request` | None | What the consent card shows for an authorization request. Query: the `/oauth/authorize` query. Returns `{ok:true, client:{id, name, kind}, redirect_host, signed_in, user}` or `{ok:false, error, error_description, redirect}`. |\n| POST | `/api/oauth/approve` | Session only (+CSRF) | Body: `{query, allow}` where `query` is the authorization request query. Returns `{ok:true, redirect}`: the client\'s redirect URI with a `code` when `allow` is `true`, else with `error=access_denied`. An invalid request returns `{ok:false, error, error_description, redirect}`. `401` without a session. |\n| GET | `/api/oauth/clients` | Session or key (`admin`) | `{clients:[{client_id, name, redirect_uris, kind, created_at, fetched_at}], connections:[{key_id, client_id}]}`. `kind` is `dcr` (registered), `cimd` (metadata document), or `manual` (added by the owner). |\n| POST | `/api/oauth/clients` | Session or key (`admin`, +CSRF) | Registers a client by hand. Body: `{name?, redirect_uris}`. Returns `{ok, client}`. `400` for invalid redirect URIs. |\n| POST | `/api/oauth/clients/delete` | Session or key (`admin`, +CSRF) | Forgets a client and its refresh tokens. Body: `{client_id}`. Returns `{ok, deleted}`. Keys issued to the client stay until they are deleted. |\n\nA `client_id` may also be an HTTPS URL of a client metadata document. The\nserver fetches it (public addresses only, no redirects, at most 64 KiB), checks\nthat its `client_id` matches the URL, and caches it for 24 hours.\n\n## Logs and activity\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/logs` | Session or key (`read`) | `{range, count, events}`, newest first, each event with a local `time`. Query: `range` (for example `1d`, `7d`, `today`, `yesterday`, `all`; default `1d`), `days` (used when `range` is absent, at most 7), `since` and `until` (unix seconds; override `range`), `limit` (default 400, max 2000), `actor`, `q`. |\n| GET | `/api/logs/settings` | Session or key (`admin`) | `{max_mb, max_days, stats:{bytes, lines, oldest, newest, max_bytes, max_days}}` for the vault event log. |\n| POST | `/api/logs/settings` | Session or key (`admin`, +CSRF) | Body: `{max_mb?, max_days?}` (1 to 512 MB; 0 to 3650 days, 0 meaning no age limit). Returns the same shape as `GET`. The log is trimmed to the new limits at once. `400` for out-of-range values. |\n| GET | `/api/events` | Session or key (`read`) | `{events, count}`: the vault event log (`.events.jsonl`), oldest first, the newest `limit` entries. Query: `since` (unix seconds), `folder`, `actor` (the key name for agents), `limit` (default 100, max 2000). |\n\n### Realtime\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/ws` | Session only | WebSocket upgrade. The `Origin` must be same-origin (`403` otherwise). `503` when too many clients are connected. |\n| POST | `/_bus` | Loopback only | Publishes a JSON object (at most 64 KiB) into the event stream. Returns `{ok:true}`. `403` for callers that are not on the same machine or that come through a proxy (any forwarding header), `400` for a body that is not a JSON object, `413` for a body or event that is too large. |\n\nOn connect the server sends a `hello` event with the client count, replays the\nlast 40 stored events (each marked `replay: true`), then streams live events.\nWhen a client leaves, the others get a `presence` event with the new count.\nMessages from the client are ignored; the server pings every 30 seconds and\ncloses a connection that has been silent for 75 seconds.\n\n### `ai_activity` events\n\nEvery MCP `tools/call` publishes a `start` and an `end` event sharing `call_id`:\n\n```json\n{"type":"ai_activity","phase":"start","call_id":"c1a2b3c4d5e6-0","actor":"research-bot",\n "actor_kind":"agent","actor_id":"k_1a2b3c4d","action":"read_memory","label":"Plan/Index.md",\n "paths":["Plan/Index.md"],"_ts":1760600000.12}\n{"type":"ai_activity","phase":"end","call_id":"c1a2b3c4d5e6-0","actor":"research-bot",\n "actor_kind":"agent","actor_id":"k_1a2b3c4d","action":"read_memory","label":"Plan/Index.md",\n "paths":["Plan/Index.md"],"ok":true,"ms":2,"_ts":1760600000.12}\n```\n\n- `actor`: the API key\'s name (fallback: key id) with `actor_kind: "agent"`; for a\n browser session the username with `actor_kind: "user"`. `actor_id` is the key id (or\n the username). Node events (`node_created`, ...) from the call carry the same `actor`.\n- `action`: the tool name.\n- `paths`: vault-relative note paths from the arguments (`path`, `paths`, `from`, `to`,\n `old_path`, `new_path`, `into` of `merge_memory`, `source`/`target` of `find_path`)\n plus note paths found in the result (search hits, the created or moved note), at\n most 20, each at most 512 bytes (longer paths are dropped). Whole-vault overviews\n (`get_graph`, `list_memory`, logs, ...) add no result paths.\n- Read-only tools publish `start` after running (so it carries the result paths),\n immediately followed by `end`; mutating tools publish `start` before running and `end`\n after, with the result paths added.\n- `end` adds `ok`, `ms`, and on failure `error` (at most 200 characters). `label` is at\n most 160 characters. `_ts` is the publish time in unix seconds. `end` events are\n realtime only: they are not written to `.events.jsonl` or the replay buffer.\n\n## UI layout\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/ui/layout/{name}` | Session only | `{name, data, updated_at}`; `data` and `updated_at` are `null` if never saved. |\n| PUT | `/api/ui/layout/{name}` | Session only (+CSRF) | `{ok:true, updated_at}`. Body: `{data: <any JSON>}`. |\n\n`name` is `[a-z0-9_-]{1,40}` (else `400`). API keys get `403`. `data` is stored as\nserialized JSON of at most 512 KiB (`413` above); the request body limit is 600 KiB.\nLayouts are stored in the `ui_layout` table of `memora.db`. The web UI uses them for\n`canvas` (card positions and frames) and `graph` (pinned positions).\n\n## Pins\n\nThe owner\'s pinned notes and folders (the sidebar\'s Pinned list), shared by every\nbrowser and device of the instance.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/pins` | Session only | `{count, pins:[{kind, path, position, missing}]}` in display order. |\n| PUT | `/api/pins` | Session only (+CSRF) | Same as GET. Body: `{pins:[{kind, path}]}`, the whole ordered list (reorder, remove). |\n| POST | `/api/pins/pin` | Session only (+CSRF) | Same as GET. Body: `{kind, path, position?}`. Pins an existing note or folder at `position` (default: the end), or moves its pin there; `404` if it does not exist. |\n| POST | `/api/pins/unpin` | Session only (+CSRF) | Same as GET plus `removed`. Body: `{kind, path}`. |\n\n`kind` is `note` or `folder`. `path` is vault-relative as the tree shows it (notes end in\n`.md`): absolute paths, `..`, empty or hidden segments, `\\`, control characters and paths\nover 1024 characters get `400`, as do more than 200 pins. API keys get `403` (agents use\nthe MCP tools `list_pins`, `pin` and `unpin`). Bodies are limited to 256 KiB for `PUT`\nand 8 KiB for `pin`/`unpin` (`413`). `missing` is true when the path no longer exists,\nfor example after a rename outside Memora; such a pin is kept until it is removed.\n\nRenames, moves and deletes done by Memora (HTTP or MCP) rewrite or drop pins in the same\ndatabase transaction, including pins on notes and folders inside a moved folder;\nmoving an item to the trash or deleting it removes its pin, and deleting a folder\nremoves every pin under it. Every change publishes a `pins_changed` realtime event with\nno other data; open browsers reload the list. Pins are stored in the `pin` table of\n`memora.db`.\n\n## Status codes\n\n| Code | Meaning |\n|---|---|\n| 200 | Success. |\n| 201 | OAuth client registered. |\n| 202 | MCP notification accepted. |\n| 204 | `/favicon.ico`. |\n| 302 | Redirect (pages to `/login` without a session, `/login` to `/` when signed in, logout to `/login`, locked instance to `/login?locked=1`, `/oauth/authorize` to the consent page). |\n| 304 | Not modified (`/api/vault/file`, static assets). |\n| 400 | Bad request, for example a missing required field or an invalid value. |\n| 401 | Missing or invalid credentials, or a session-only endpoint called without a session. |\n| 403 | Blocked by an access rule, a CSRF origin mismatch, a missing key scope, a wrong password or setup code, or an endpoint that needs an open setup or reset window. |\n| 404 | Note, key, session, rule, or route not found; also any request for a host outside the domain list. |\n| 405 | `/mcp` called with a method other than `POST`. |\n| 408 | The request took longer than 30 seconds. |\n| 409 | No vault configured (`needs_vault: true`), or a state conflict. |\n| 413 | Body, layout, image, or event too large. |\n| 415 | `/api/vault/file` path is not an image. |\n| 423 | Instance is LOCKED. |\n| 429 | Rate limit or failed-attempt cooldown (`Retry-After` header). |\n| 500 | Internal error, for example the state database failed. |\n| 503 | UI assets are not installed, the password hashing pool is busy, or too many realtime clients. |\n',ON=`# Deployment
9683
+ `,$N="# Installing Memora\n\nMemora ships as two binaries plus a folder of web UI assets:\n\n| Piece | Role |\n|---|---|\n| `memora` | The server: HTTP API, MCP, web UI, and WebSocket on **one TCP port** (default `8400`) |\n| `memora-cli` | The operator console. Run it with no arguments for slash commands (`/guide`, `/web`, `/config`, ...) |\n| `assets/` | Web UI files, found through `MEMORA_ASSETS` |\n\nThere are two supported ways to run it as a service: **native** (systemd, via\n`install.sh`) and **Docker** (Compose). On Linux it can also be installed with\n**npm**, which is handy for trying it or running it under your own user. All\nend the same way: open the console, type `/web`, and finish setup in the\nbrowser.\n\n**Fastest path** (pick one, in this order of ease), then open the link the\nsetup command prints and enter the code:\n\n```bash\n# npm (Linux x86_64 / arm64, Node 18+)\nnpm install -g @codrihub/memora && memora\nmemora-cli setup --minutes 15 # in a second terminal\n\n# Docker: no clone or folder permissions needed (named volumes)\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\ndocker exec -it memora memora-cli setup --minutes 15\n\n# Native installer (Linux server with systemd)\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\nsudo memora-cli setup --minutes 15\n```\n\n- [Network exposure](#network-exposure)\n- [Native install](#native-install)\n- [Docker](#docker)\n- [npm](#npm)\n- [Windows zip](#windows-zip)\n- [Reverse proxy](#reverse-proxy)\n- [Backups](#backups)\n- [Automation: `--check` and `--upgrade`](#automation---check-and---upgrade)\n\n## Network exposure\n\nMemora opens exactly **one TCP port**. The HTTP API, MCP (`/mcp`), the web UI,\nand the realtime WebSocket (`/ws`) all share it. The local event intake\n`/_bus` answers on the same port but only to loopback clients.\n\nThe state database is embedded SQLite (`<state>/memora.db`). The server creates\nand migrates it on first start; it opens no port and needs no separate\ndatabase server or install.\n\nNothing else listens. Allow only that one port through the firewall, or none at\nall when a reverse proxy on the same host is the entry point\n(`--behind-proxy`).\n\n## Native install\n\nRequirements: Linux on x86_64 or aarch64 with systemd, `curl` (or `wget`),\n`tar`, `sha256sum`, and `git` (vault history uses it).\n\n```sh\n# Inspect first: https://github.com/Codrihub/memora/blob/main/scripts/install.sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nPass flags after `sh -s --`, for example:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh \\\n | sudo sh -s -- --version 1.0.0 --behind-proxy\n```\n\nor download the script and run it: `sudo sh install.sh --help`.\n\nThe script is idempotent: running it again reinstalls the same files and keeps\nthe port and bind address of the existing unit unless you pass new ones.\n\n### What it does\n\n1. Downloads `memora-<version>-<arch>-linux.tar.gz` for this CPU from GitHub\n Releases (the latest, or `--version`), downloads `SHA256SUMS` from the same\n release, and refuses to continue if the checksum does not match.\n2. Installs the binaries atomically (copy to a temp file, then `mv`).\n3. Creates the system user and group `memora` (no login shell, home\n `/var/lib/memora`).\n4. Creates `/var/lib/memora/state` (`0700`) and `/var/lib/memora/vault`\n (`0750`), owned by `memora`.\n5. Writes `/etc/systemd/system/memora.service`, enables and starts it, waits\n for `/healthz`, then verifies the state database with `memora-cli db check`.\n6. Prints the next step and, when listening on every interface, a firewall\n hint.\n\n### Paths\n\n| Path | Content |\n|---|---|\n| `/usr/local/bin/memora`, `/usr/local/bin/memora-cli` | Binaries |\n| `/usr/local/share/memora/assets/` | Web UI |\n| `/usr/local/share/memora/VERSION` | Installed version (read by `--check`) |\n| `/usr/local/share/memora/install.sh` | Copy of the installer, used for `--upgrade`, `--check`, `--uninstall`, and `memora-cli update` |\n| `/var/lib/memora/state/` | `memora.db` (owner, API key hashes, sessions, settings, activity log), `backups/` |\n| `/var/lib/memora/vault/` | Suggested vault folder (chosen in the browser after the first sign-in) |\n| `/etc/systemd/system/memora.service` | The unit |\n\n`--prefix` moves the first four (default `/usr/local`), `--data-dir` moves the\nlast two (default `/var/lib/memora`).\n\n### Flags\n\n| Flag | Meaning |\n|---|---|\n| *(none)* | Install or reinstall the latest release |\n| `--version X.Y.Z` | Install that release |\n| `--from-source` | Build with `cargo build --release --locked` in the checkout the script lives in (`sudo ./scripts/install.sh --from-source`); built as `$SUDO_USER` |\n| `--from-dir PATH` | Install `PATH/memora`, `PATH/memora-cli`, `PATH/assets/` (an unpacked release, or your own build). Version from `--version`, else `PATH/VERSION` |\n| `--port N` | Port (default `8400`) |\n| `--bind ADDR` | Bind address (default `0.0.0.0`) |\n| `--behind-proxy` | Bind `127.0.0.1`; a reverse proxy on this host is the only entry |\n| `--prefix DIR` | Install prefix (default `/usr/local`) |\n| `--data-dir DIR` | Data root (default `/var/lib/memora`) |\n| `--no-start` | Install and enable, but do not start |\n| `--no-systemd` | Skip the unit and the system user (containers, tests); prints the command to start the server by hand |\n| `--upgrade` | Replace binaries and assets, keep state, restart the service if it was running |\n| `--force` | With `--upgrade`: reinstall even when already up to date |\n| `--uninstall` | Stop and remove the unit, binaries, and assets; keep data |\n| `--purge` | With `--uninstall`: also delete the data dir and the `memora` user (asks first) |\n| `--check` | Print `MEMORA_LATEST=` and `MEMORA_INSTALLED=`; change nothing |\n| `--yes`, `-y` | Never ask (needed for `--purge` without a terminal) |\n| `--dry-run` | Print every action, change nothing |\n| `--repo OWNER/NAME` | Download from another GitHub repository (forks); also settable as `MEMORA_REPO` |\n\n`MEMORA_RELEASES_URL` points the installer at a mirror that serves the same\nlayout as GitHub (`<url>/latest`, `<url>/download/vX.Y.Z/<file>`).\n\nRoot is required except for `--check`, `--dry-run`, and `--no-systemd` into a\nprefix you can write to.\n\n### Exit codes\n\n| Code | Meaning |\n|---|---|\n| `0` | Success |\n| `1` | Error (see the message) |\n| `2` | Bad usage |\n| `3` | Already up to date (`--upgrade`) |\n| `4` | Network or download failure |\n| `5` | Checksum mismatch or missing from `SHA256SUMS` |\n| `6` | Not running as root |\n| `7` | Unsupported OS or CPU |\n\n### The systemd unit\n\nThe installer writes this unit (shown with the default paths and port):\n\n```ini\n[Unit]\nDescription=Memora - long-term memory for AI agents (HTTP API + MCP + web UI)\nDocumentation=https://github.com/Codrihub/memora\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=memora\nGroup=memora\nWorkingDirectory=/var/lib/memora\nEnvironment=HOME=/var/lib/memora\nEnvironment=MEMORA_STATE=/var/lib/memora/state\nEnvironment=MEMORA_ASSETS=/usr/local/share/memora/assets\nEnvironment=MEMORA_PORT=8400\nEnvironment=MEMORA_BIND=0.0.0.0\nEnvironment=MEMORA_VAULT=/var/lib/memora/vault\nEnvironment=GIT_AUTHOR_NAME=Memora\nEnvironment=GIT_AUTHOR_EMAIL=memora@localhost\nEnvironment=GIT_COMMITTER_NAME=Memora\nEnvironment=GIT_COMMITTER_EMAIL=memora@localhost\nEnvironment=RUST_LOG=info\nExecStart=/usr/local/bin/memora\nRestart=on-failure\nRestartSec=3\nTimeoutStopSec=15\nLimitNOFILE=65536\nUMask=0027\n\n# Hardening\nNoNewPrivileges=yes\nAmbientCapabilities=\nCapabilityBoundingSet=\nProtectSystem=strict\nReadWritePaths=/var/lib/memora\nProtectHome=yes\nPrivateTmp=yes\nPrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectKernelLogs=yes\nProtectControlGroups=yes\nProtectClock=yes\nProtectHostname=yes\nRestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nRestrictNamespaces=yes\nRestrictRealtime=yes\nRestrictSUIDSGID=yes\nLockPersonality=yes\nMemoryDenyWriteExecute=yes\nSystemCallArchitectures=native\nSystemCallFilter=@system-service\nSystemCallFilter=~@privileged\n\n[Install]\nWantedBy=multi-user.target\n```\n\nA port below 1024 adds `CAP_NET_BIND_SERVICE` instead of the empty capability\nset. There are no IP restrictions (`IPAddressDeny=`) by default; use the\nfirewall, `MEMORA_DOMAIN`, or the access rules in the UI.\n\nThe installer rewrites the unit on every run. Put local changes in a drop-in:\n\n```sh\nsudo systemctl edit memora # for example, a vault outside /var/lib/memora:\n# [Service]\n# ReadWritePaths=/srv/notes\nsudo systemctl restart memora\n```\n\nBecause of `ProtectSystem=strict` and `ProtectHome=yes`, the server can only\nwrite under `/var/lib/memora`. A vault anywhere else (including `/home`) needs\nthe drop-in above (and `ProtectHome=read-only` or `no` for `/home`).\n\n### Settings\n\nThe unit sets the basics (`MEMORA_STATE`, `MEMORA_ASSETS`, `MEMORA_PORT`,\n`MEMORA_BIND`, `MEMORA_VAULT`, `RUST_LOG`) as `Environment=` lines. Everything\nelse (`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`, ...) is\nstored in the state database (table `server_config`). Edit it with the\nconsole: `sudo memora-cli` → `/config`, then `/restart`.\n\nA value stored with `/config` wins over the unit's `Environment=` lines; a key\nwith no stored value uses the environment. If you stored `MEMORA_PORT` with\n`/config` and later reinstall with `--port`, change or clear it in `/config`\ntoo, otherwise the stored value keeps applying. The provisioning owner\npassword and API key are environment-only and never stored (see\n[CONFIGURATION.md](CONFIGURATION.md)).\n\nSee [CONFIGURATION.md](CONFIGURATION.md) for every variable.\n\n### First run\n\n```sh\nsudo memora-cli # opens the console; it finds the running server itself\n/guide # step-by-step, or:\n/web # prints a one-time code\n```\n\nOpen `http://<host>:8400/login`, enter the code, create the owner account, then\nchoose the vault folder (`/var/lib/memora/vault` is suggested).\n\n### Day to day\n\n```sh\nsudo systemctl status memora\nsudo systemctl restart memora\nsudo journalctl -u memora -f\nsudo memora-cli # /status, /keys, /config, /restart, /mcp ...\n```\n\n### Upgrading\n\n```sh\nsudo /usr/local/share/memora/install.sh --upgrade # latest release\nsudo /usr/local/share/memora/install.sh --upgrade --version 1.0.1\nsudo memora-cli update # same, from the console\n```\n\nBinaries and assets are swapped atomically, the state directory and vault are\nuntouched, and the service is restarted if it was running. The server migrates\n`memora.db` itself on start. Take a `memora-cli db backup` before upgrading,\nand read the [CHANGELOG](../CHANGELOG.md) before a major version bump.\n\n### Uninstall\n\n```sh\nsudo /usr/local/share/memora/install.sh --uninstall # keeps /var/lib/memora and the memora user\nsudo /usr/local/share/memora/install.sh --uninstall --purge # also deletes notes, account, keys, and the user\n```\n\n### Firewall\n\nOpen only the Memora port, and only when clients connect directly:\n\n```sh\nsudo ufw allow 8400/tcp\n# or\nsudo firewall-cmd --permanent --add-port=8400/tcp && sudo firewall-cmd --reload\n```\n\nBehind a reverse proxy on the same host, install with `--behind-proxy` and open\nonly the proxy's 80/443.\n\n## Docker\n\n```sh\ngit clone https://github.com/Codrihub/memora.git && cd memora\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ndocker compose exec -it gateway memora-cli # then /guide, or /web\n```\n\n`docker compose up` pulls `ghcr.io/codrihub/memora:<version>`; if the image is\nnot available (or you set `IMAGE=memora:local`) it builds from the\n`Dockerfile`. Image tags: `<version>` (for example `1.0.0`), `<major>.<minor>`\n(for example `1.0`), and `latest` (stable releases only), for `linux/amd64`\nand `linux/arm64`. The compose file pins the release it ships with; set\n`IMAGE` in `.env` to run another tag.\n\n### Volumes: `/data` and `/state`\n\nBoth must be persistent (the Compose file bind-mounts `./data` and `./state`):\n\n- `/data` is the vault: your notes, their git history, the search index, and\n the event log. Lose it and the notes are gone.\n- `/state` holds `memora.db` (owner account, password hash, API key hashes,\n sessions, settings, setup/lock state, activity log). Lose it and\n every agent key stops working, the instance falls back to first-run setup,\n and anyone who reaches the port during that window could claim it.\n\nThe container runs as uid 1000; set `MEMORA_UID`/`MEMORA_GID` in `.env` if the\nhost directories belong to another user. `MEMORA_DATA_DIR` and\n`MEMORA_STATE_DIR` move the host directories, and `MEMORA_HTTP_PORT` changes\nthe published host port. See [CONFIGURATION.md](CONFIGURATION.md#docker-compose-env).\n\n### Verify\n\n```sh\ncurl -s http://127.0.0.1:8400/healthz\ndocker compose exec gateway memora-cli db check\ndocker compose exec gateway memora-cli status\nls -l state/memora.db\n```\n\n### Upgrading\n\n```sh\ngit pull\ndocker compose pull && docker compose up -d # or: docker compose up -d --build\n```\n\nSettings: `docker compose exec -it gateway memora-cli` → `/config`, then\n`docker compose restart gateway` (`/restart` cannot restart a container from\ninside).\n\n## npm\n\nRequirements: Linux on x86_64 or arm64, or Windows 10/11 on x64; Node 18 or\nnewer; and `git` (vault history uses it).\n\n```sh\nnpm install -g @codrihub/memora\nmkdir -p ~/memora && cd ~/memora\nMEMORA_VAULT=./vault MEMORA_STATE=./state memora\n# in a second terminal, same folder:\nMEMORA_STATE=./state memora-cli # then /guide, or /web\n```\n\nOn Windows, in PowerShell:\n\n```powershell\nnpm install -g @codrihub/memora\nmkdir ~\\memora; cd ~\\memora\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; memora\n# in a second terminal, same folder:\n$env:MEMORA_STATE = '.\\state'; memora-cli # then /guide, or /web\n```\n\n`npx @codrihub/memora --version` runs it without a global install.\n\n`@codrihub/memora` holds the `memora` and `memora-cli` commands and the web UI\n(used unless `MEMORA_ASSETS` is set). The binaries come from\n`@codrihub/memora-linux-x64`, `@codrihub/memora-linux-arm64` or\n`@codrihub/memora-win32-x64`, optional dependencies npm installs only on a\nmatching machine. The Linux ones are the static binaries of the GitHub\nrelease with the same version, so glibc and musl distributions both work; the\nWindows one is built with a static C runtime and needs nothing else. There is\nno install script and nothing is downloaded at install time, so it works with\n`--ignore-scripts` and from a registry mirror; it does not work with\n`--omit=optional`, which leaves the binaries out. On macOS the commands print\nwhere to go instead: use [Docker](#docker) or build from source.\n\nThe npm install sets up no service, user or data folder: the server runs as\nyou, with `MEMORA_STATE` and `MEMORA_VAULT` where you point them (`./state`\nby default). Keep the state folder private (`chmod 700 state`; on Windows,\nkeep it under your user profile), since it holds the owner account and key\nhashes. On Windows, `memora-cli` runs every command as you: there is no root\nor service account to switch to. For a long-running server, prefer the\n[native install](#native-install).\n\nUpgrade with `npm install -g @codrihub/memora@latest` (`memora-cli update`\nprints this too) and restart the server; the state database is migrated on\nstart.\n\n## Windows zip\n\nEach GitHub release also carries `memora-<version>-x86_64-windows.zip`:\n`memora.exe`, `memora-cli.exe`, the web UI (`assets\\`), `LICENSE` and this\nREADME. It needs no installer, Node or runtime (static C runtime), and\n`memora.exe` finds the `assets` folder next to it. Check the download against\nthe release `SHA256SUMS` (`Get-FileHash memora-*.zip`), unzip it, then in\nPowerShell:\n\n```powershell\ncd memora-<version>-x86_64-windows\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; .\\memora.exe\n# in a second window, same folder:\n$env:MEMORA_STATE = '.\\state'; .\\memora-cli.exe setup --minutes 15\n```\n\nOpen `http://localhost:8400/login` and enter the code. Like the npm install,\nit runs as you with no service; keep the folder under your user profile.\n\n## Reverse proxy\n\nRun Memora on loopback (`--behind-proxy` natively; in Docker set\n`MEMORA_HTTP_PORT=127.0.0.1:8400` in `.env`) and let the proxy terminate TLS.\nThen set, with `/config` or in `.env`:\n\n| Variable | Why |\n|---|---|\n| `MEMORA_BASE_URL=https://memory.example.com` | Public URL; links and MCP snippets use it, and its host becomes an allowed domain |\n| `MEMORA_DOMAIN=memory.example.com` | Only these hostnames are served; requests for the bare IP or other names get 404 |\n| `MEMORA_TRUSTED_PROXIES=203.0.113.10` | Proxies whose forwarding headers are believed. Loopback (same-host nginx, cloudflared) is always trusted; only list remote proxies |\n\nIn Docker, a proxy on the host reaches the container through the Docker\nnetwork, so the container sees the network's gateway address (for example\n`172.18.0.1`) instead of loopback. Add that address to\n`MEMORA_TRUSTED_PROXIES`, otherwise every request appears to come from it.\n\nThe proxy must forward `Host`, `X-Forwarded-For`, and `X-Forwarded-Proto`, and\nupgrade WebSockets on `/ws`. nginx and Caddy examples are in\n[DEPLOYMENT.md](DEPLOYMENT.md).\n\n## Backups\n\nBack up **both** the state database and the vault. The database is small but\ncritical.\n\nState, online (the server keeps running):\n\n```sh\nsudo memora-cli db backup # state/backups/memora-<UTC time>.db, keeps the newest 10\nsudo memora-cli db backup --to /var/backups/memora.db\nsudo memora-cli db check # integrity, permissions, sizes, last backup age\ndocker compose exec gateway memora-cli db backup # Docker: lands in ./state/backups/\n```\n\nThe copy is a consistent snapshot (`VACUUM INTO`), checked with\n`integrity_check`, mode 0600. Never `cp` a live `memora.db`: recent commits sit\nin `memora.db-wal`. Restore with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo memora-cli db restore /var/backups/memora.db # verifies it; keeps the replaced DB in state/backups/\nsudo systemctl start memora\n```\n\nAlso keep a copy of `state/key-seal.bin`, which encrypts the sealed API key\ncopies. Vault and state together: archive both with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo tar -C /var/lib/memora -czf memora-backup-$(date +%F).tar.gz state vault\nsudo systemctl start memora\n```\n\nKeep backups private: the database holds password and key hashes (never\nplaintext secrets).\n\n## Automation: `--check` and `--upgrade`\n\nThese are the contract for scripts and automation.\n\n```sh\n$ /usr/local/share/memora/install.sh --check\nMEMORA_LATEST=1.0.1\nMEMORA_INSTALLED=1.0.0\n```\n\n`MEMORA_INSTALLED` comes from `/usr/local/share/memora/VERSION` (written by\nthe installer), else from `memora --version`, else `unknown` (or `none` when\nnothing is installed). `MEMORA_LATEST` is `unknown` and the exit code `4` when\nGitHub cannot be reached. `--check` needs no root.\n\n```sh\n$ sudo /usr/local/share/memora/install.sh --upgrade --yes [--version X.Y.Z]\n...\nMEMORA_UPGRADE_RESULT=ok FROM=1.0.0 TO=1.0.1\n```\n\n`--upgrade --yes` never prompts. The last line of output is always\n`MEMORA_UPGRADE_RESULT=<ok|uptodate|error> FROM=<old> TO=<new>`, and the exit\ncode is `0` (ok), `3` (already up to date), `4` (network), `5` (checksum),\n`6` (not root), or `1`/`2` for other errors.\n",NN="# Configuration\n\nAll server state, settings included, lives in one SQLite database,\n`<MEMORA_STATE>/memora.db` (see [DATABASE.md](DATABASE.md)). Server settings are\nrows in the `server_config` table, edited with `memora-cli` (`/config` in the\nconsole). The process environment (systemd `Environment=`, Docker\n`environment:`) applies to every key that has no row.\n\n## Precedence\n\nFor each server setting:\n\n1. a row in `server_config` (set with `/config`), else\n2. the process environment (non-empty value), else\n3. the built-in default.\n\nThe server reads `server_config` once at startup, before anything else, so a\nchange made with `/config` applies after a restart (`/restart` for a native\ninstall, `docker compose restart gateway` in Docker). Clearing a value in\n`/config` deletes the row, and the environment or default applies again.\n\nA row wins over the environment. If you set `MEMORA_PORT` with `/config` and\nlater change the port in the systemd unit or `.env`, the row still applies\nuntil you clear it.\n\n## Server settings\n\n| Name | Default | Where it can live | What it does |\n|---|---|---|---|\n| `MEMORA_PORT` | `8400` | `server_config` or env | HTTP port (API, MCP, web UI, WebSocket). 1-65535. |\n| `MEMORA_BIND` | `127.0.0.1` | `server_config` or env | Bind address. `0.0.0.0` for every interface (the container image and the installer set it). |\n| `MEMORA_BASE_URL` | empty | `server_config` or env | Public URL, for example `https://memory.example.com`. Used for OAuth metadata and connection snippets; its host is also an allowed domain. |\n| `MEMORA_DOMAIN` | empty (any host) | `server_config` or env | Allowed hostnames, comma separated (`*.example.com` works). Requests for other hosts get 404. Loopback names are always allowed. |\n| `MEMORA_TRUSTED_PROXIES` | empty | `server_config` or env | IPs of remote reverse proxies whose forwarding headers are trusted. Loopback is always trusted. |\n| `MEMORA_ARM_TTL` | `300` | `server_config` or env | Accepted and validated (30-86400 seconds), but the server and `memora-cli` do not read it: the setup / reset window length comes from `memora-cli --minutes` (default 5 minutes). |\n| `MEMORA_VAULT` | empty (`data` as last resort) | `server_config` or env | Suggested vault folder. The vault in use is chosen in the browser (or with `memora-cli vault`) and stored in the `settings` table. |\n| `MEMORA_VAULT_AUTO` | `false` | `server_config` or env | `true` (also `1`, `yes`, `on`): use `MEMORA_VAULT` at startup instead of asking in the browser, only while no vault is configured and if the folder is writable. |\n| `MEMORA_ADMIN_USER` | `admin` | `server_config` or env | Name of the owner created at startup when no owner exists (needs `MEMORA_ADMIN_PASSWORD`). |\n| `RUST_LOG` | `info` | `server_config` or env | Log filter, for example `info` or `memora=debug`. |\n\n`server_config` accepts only these ten keys. Values are trimmed and validated\n(numbers in range, `true`/`false`, a valid user name, no control characters, at\nmost 2048 bytes).\n\n## Environment only\n\n| Name | Default | What it does |\n|---|---|---|\n| `MEMORA_ADMIN_PASSWORD`, `MEMORA_ADMIN_PASSWORD_FILE` | unset | Creates the owner at startup when none exists (at least 10 characters). Only the argon2id hash is stored; an existing owner is never replaced. |\n| `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE` | unset | Installs an agent API key with id `k_env` and scopes `mcp`, `read`, `write` (at least 24 characters). Only its SHA-256 is stored; the key is replaced when the value changes. |\n| `MEMORA_STATE` | `state` (relative to the working directory) | State directory holding `memora.db`. Created with mode 0700 if missing. |\n| `MEMORA_ASSETS` | the `crates/http/assets` folder of the build tree | Directory of the web UI assets. |\n| `MEMORA_SETUP_HINT` | `memora-cli setup (run on the server)` | Hint returned by `GET /api/auth/state` and shown on the login screen. |\n| `MEMORA_UPDATE_CHECK` | `true` | Release check: shortly after start and then every 6 hours the server asks GitHub (`api.github.com/repos/Codrihub/memora/releases/latest`) for the newest release and the web UI shows when an update is available. `false` (also `0`, `no`, `off`) turns it off; no network call is made. |\n\nThe two secrets can never be stored in `server_config` (the schema rejects\nthem). The `_FILE` variants read the value from a file, for example a Docker\nsecret; a non-empty file wins over the plain variable.\n\nIn `/config`, `MEMORA_API_KEY` offers to create an API key directly, and\n`MEMORA_ADMIN_PASSWORD` points to `/setup` or `/reset`.\n\n## Instance settings (web UI)\n\nThe `settings` table holds one row, edited from the Settings page of the web UI:\n\n| Key | Default | Range | What it does |\n|---|---|---|---|\n| `realm` | `Memora` | 1-64 characters | Instance name shown in the UI and reported by `/api/config` and `/api/auth/state`. |\n| `session_ttl` | `10800` (3 hours) | 300-2592000 seconds | Idle timeout of a browser session. |\n| `session_max_age` | `0` | `0` or at least `session_ttl` | Absolute session lifetime in seconds. `0` means no cap. |\n| `min_password_len` | `10` | 10-256 | Minimum owner password length. |\n| `log_max_mb` | `8` | 1-512 | Size limit in MB of the vault event log (`.events.jsonl`). |\n| `log_max_days` | `0` | 0-3650 | Age limit in days of the vault event log. `0` means no age limit. |\n| `vault_path` | unset | absolute path | The vault folder. Set in the browser after the first sign-in, or with `memora-cli vault PATH`. |\n\n## memora-cli options\n\n| Option | Default | What it does |\n|---|---|---|\n| `--state <DIR>` | `$MEMORA_STATE`, else the state directory of the running `memora` server, else `./state` | State directory to work on. |\n| `--minutes <N>` | `5` | Window length for `setup` and `reset-password`, 1-60. |\n| `--ttl <SECONDS>` | | Window length in seconds (at most 3600). `--minutes` wins when both are given. |\n| `--create` | | With `vault PATH`: create the folder if it does not exist. |\n\nRun as root, `memora-cli` does all database work as the owner of the state\ndirectory, so no root-owned `memora.db*` files appear. See\n[INSTALL.md](INSTALL.md) and [DEPLOYMENT.md](DEPLOYMENT.md) for the commands.\n\n## Docker Compose (`.env`)\n\nThese variables are read by `docker-compose.yml`, not by Memora itself:\n\n| Name | Default | What it does |\n|---|---|---|\n| `COMPOSE_PROJECT_NAME` | `memora` | Compose project name, also the container name prefix. |\n| `IMAGE` | `ghcr.io/codrihub/memora:<version>` | Image to run or build. The compose file pins the release it ships with. |\n| `MEMORA_HTTP_PORT` | `8400` | Host port mapped to the container's port 8400. Use `127.0.0.1:8400` to publish on loopback only. |\n| `MEMORA_DATA_DIR` | `./data` | Host path mounted at `/data` (the vault). |\n| `MEMORA_STATE_DIR` | `./state` | Host path mounted at `/state` (the state directory). |\n| `MEMORA_UID`, `MEMORA_GID` | `1000` | uid:gid the container runs as. Must own both host directories. |\n| `MEMORA_ARM_TTL` | `300` | Passed to the container unchanged. |\n\nCompose also passes these through from `.env` to the container:\n`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`,\n`MEMORA_VAULT_AUTO`, `MEMORA_ADMIN_USER`, `MEMORA_ADMIN_PASSWORD`,\n`MEMORA_ADMIN_PASSWORD_FILE`, `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE`,\n`MEMORA_SETUP_HINT`, `MEMORA_UPDATE_CHECK`, and `RUST_LOG`.\n\nInside the container the image sets `MEMORA_VAULT=/data`,\n`MEMORA_STATE=/state`, `MEMORA_PORT=8400`, `MEMORA_BIND=0.0.0.0`,\n`MEMORA_ARM_TTL=300`, `MEMORA_ASSETS=/app/assets`, and `RUST_LOG=info`.\n\n## State directory\n\n| Path | Content |\n|---|---|\n| `memora.db` (+ `-wal`, `-shm`) | The state database: owner, API keys (hashes), tool switches and per-key permissions, OAuth clients and grants, privacy rules, sessions (hashed ids), setup window and lock state, access rules, settings, `server_config`, activity log. Mode 0600, WAL mode, must be on a local filesystem. See [DATABASE.md](DATABASE.md). |\n| `key-seal.bin` | 32-byte master key (mode 0600) that encrypts the copies of dashboard-created API keys, so the owner can show a key again. Created on first use. Back it up together with `memora.db`. |\n| `backups/` | `memora-cli db backup` output (newest 10 kept by default). |\n| `legacy-json-<unix time>/` | JSON state files found at startup, moved here after their one-time import into `memora.db`. |\n| `internal.token` | Created by the Docker entrypoint. Not used by Memora. |\n\n## Vault files\n\nThe vault holds the markdown notes plus derived and metadata files. See\n[ARCHITECTURE.md](ARCHITECTURE.md#vault-markdown-portable) for the full list.\nThe important ones for operations are `.git/` (history), `.fts.db`\n(rebuildable search index), `.events.jsonl` (event log), and `.Trash/`\n(soft-deleted notes).\n",DN='# MCP\n\nMemora exposes the vault to agents through the Model Context Protocol. The\nserver speaks JSON-RPC 2.0 over the Streamable HTTP transport at `/mcp`, on the\nsame port as the HTTP API and the web UI. There is one MCP endpoint and one tool\ncatalog.\n\n| | |\n|---|---|\n| Endpoint | `POST /mcp` |\n| Protocol versions | `2025-06-18` (preferred), `2025-03-26`, `2024-11-05` |\n| Auth | API key in `Authorization: Bearer <key>` or `X-API-Key: <key>`, or an OAuth 2.1 access token |\n| Discovery card | `GET /.well-known/mcp.json` (public) |\n| Readable catalog | `GET /tools` (HTML page, public) |\n| Catalog size | 74 tools, plus 5 admin tools for keys with the `admin` scope |\n\n`initialize` answers with the protocol version the client asks for when it is\none of the three above, and with `2025-06-18` otherwise.\n\n## Transport\n\n- Requests are JSON-RPC 2.0 objects sent with `POST /mcp`. Batches (JSON\n arrays) are not supported.\n- Responses are plain JSON (`application/json`). The server does not open SSE\n streams and does not issue an `Mcp-Session-Id`.\n- `GET` and `DELETE` on `/mcp` return `405 Method Not Allowed` with\n `Allow: POST`.\n- A notification (a `notifications/*` method without an `id`) gets\n `202 Accepted` and no body.\n- `/mcp` needs a configured vault. Until one is chosen it returns\n `409 {"error":"vault not configured","needs_vault":true}`.\n- A browser session (cookie) may also call `/mcp`. It then needs a same-origin\n request, like the rest of the JSON API.\n\nThe server speaks Streamable HTTP only. A client that can only launch local stdio\nservers can use a bridge such as `mcp-remote` (see below).\n\n## Connecting an agent\n\n### With an API key\n\nCreate a key in the web UI (Keys page), with `memora-cli` (`/keys`), or with\n`POST /api/keys`. The raw key (`memora_live_...`) is shown once. By default a key gets\nthe scopes `mcp`, `read` and `write` and may call every tool. See\n[Tool switches and per-key permissions](contracts/tools-permissions.md) to\nnarrow it.\n\nUse `http://localhost:8400/mcp` for a local install, or your public URL such as\n`https://memory.example.com/mcp` behind a reverse proxy. When the server sets\n`MEMORA_DOMAIN` or `MEMORA_BASE_URL`, requests for any other host get `404`, so\nuse that domain.\n\nClaude Code:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp \\\n --header "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n```\n\nCursor, Windsurf and other clients with an `mcpServers` JSON config (VS Code\nuses the key `servers` in `.vscode/mcp.json`):\n\n```json\n{\n "mcpServers": {\n "memora": {\n "type": "http",\n "url": "http://localhost:8400/mcp",\n "headers": {\n "Authorization": "Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n }\n }\n }\n}\n```\n\nCodex (`~/.codex/config.toml`), with the key in the `MEMORA_API_KEY`\nenvironment variable:\n\n```toml\n[mcp_servers.memora]\nurl = "https://memory.example.com/mcp"\nbearer_token_env_var = "MEMORA_API_KEY"\n```\n\nClients that only run local stdio servers, such as the Claude Desktop config\nfile, can bridge with `mcp-remote` (needs Node.js):\n\n```json\n{\n "mcpServers": {\n "memora": {\n "command": "npx",\n "args": [\n "-y", "mcp-remote", "https://memory.example.com/mcp",\n "--header", "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n ]\n }\n }\n}\n```\n\nSome clients send the key as `X-API-Key: <key>` instead. Both headers are\naccepted.\n\n### With OAuth\n\nClients that support MCP authorization (for example Claude and ChatGPT custom\nconnectors, or Claude Code without a `--header`) can connect with only the URL:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp\n```\n\nThe flow:\n\n1. The client calls `/mcp` without credentials and gets `401` with\n `WWW-Authenticate: Bearer resource_metadata="https://memory.example.com/.well-known/oauth-protected-resource"`.\n2. It reads the protected resource metadata (RFC 9728) and the authorization\n server metadata at `/.well-known/oauth-authorization-server` (RFC 8414; also\n served at `/.well-known/openid-configuration` and under a `/mcp` suffix).\n3. It registers itself with dynamic client registration at\n `POST /oauth/register` (RFC 7591), or uses an HTTPS client metadata document\n URL as its `client_id`. The owner can also register clients in the web UI.\n Redirect URIs must be HTTPS, or plain HTTP on `localhost`, `127.0.0.1` or\n `[::1]`.\n4. It opens `/oauth/authorize` (authorization code with PKCE `S256` only). The\n browser lands on the Memora sign-in page, and the signed-in owner approves or\n denies the connection on a consent card. Codes are valid for 10 minutes.\n5. It exchanges the code at `POST /oauth/token` and receives an access token and\n a refresh token. The only OAuth scope is `mcp`.\n\nThe access token is a regular Memora API key named after the client. It starts\nwith the default scopes (`mcp`, `read`, `write`) and every tool, and it shows up\non the Keys page like any other key, so you can restrict, disable or delete it\nthere. The access token has no expiry. A `refresh_token` grant replaces it with\na fresh one (the old token stops working at once) and rotates the refresh token.\nDisabling or deleting the key ends the connection.\n\nSet `MEMORA_BASE_URL` (for example `https://memory.example.com`) when the server\nruns behind a proxy, so the issuer and endpoint URLs in the metadata are the\npublic ones. Without it the server derives them from the request headers.\n\n### Test from a shell\n\n```bash\ncurl -s -X POST http://localhost:8400/mcp \\\n -H "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY" \\\n -H "Content-Type: application/json" \\\n -d \'{"jsonrpc":"2.0","id":1,"method":"tools/list"}\'\n```\n\n## Discovery card\n\n`GET /.well-known/mcp.json` needs no auth and returns:\n\n| Field | Value |\n|---|---|\n| `name` | `memora` |\n| `version` | The server version |\n| `description` | One-line description of the server |\n| `mcp` | `{endpoint: "/mcp", transports: ["streamable-http"], protocolVersion: "2025-06-18"}` |\n| `auth` | `{type: "api-key", headers: ["Authorization: Bearer <key>", "X-API-Key: <key>"], oauth: "/.well-known/oauth-authorization-server"}` |\n| `capabilities` | `{tools: true, resources: true, prompts: false}` |\n| `tools` | Every catalog tool as `{name, category, description, enabled}`. `enabled` is `false` for tools switched off on this server. Admin tools are not listed. |\n| `resources` | `[{uri, name}]` for the three resources below |\n\nThe card is the same for every caller. To see what a given key may call, use\n`tools/list` with that key.\n\n## Methods\n\n| Method | Purpose |\n|---|---|\n| `initialize` | Handshake. Returns `protocolVersion`, `serverInfo` (`{name, version}`) and `capabilities` (`tools` and `resources`, both with `listChanged: false`). |\n| `notifications/initialized` | Client notification. Without an `id` it gets `202 Accepted`. |\n| `tools/list` | The tools the caller may use, each with `name`, `description` (what it does and when to use it), `inputSchema`, and `_meta.category`. |\n| `tools/call` | Runs one tool. Params are `{name, arguments}`. |\n| `resources/list` | Lists the three resources below. |\n| `resources/read` | Reads one resource. Params are `{uri}`. |\n\nThere are no prompts, no pagination cursors and no change notifications.\n\n### Resources\n\n| URI | Content |\n|---|---|\n| `memory://catalog` | Every catalog tool with `name`, `category`, `description`, `when`, and `inputSchema` (JSON) |\n| `memory://schema` | Data shapes for a note, a folder, the graph, and activity (JSON) |\n| `memory://guide` | A short guide for agents using the vault (Markdown) |\n\n`resources/read` returns `{contents: [{uri, mimeType, text}]}`.\n\n## Results and errors\n\nA successful tool call returns the tool\'s JSON result as text:\n\n```json\n{\n "jsonrpc": "2.0",\n "id": 2,\n "result": {\n "content": [{ "type": "text", "text": "{...}" }],\n "isError": false\n }\n}\n```\n\nA tool that fails (bad arguments, note not found, unknown tool name) returns the\nsame envelope with `isError: true` and the error message as the text. The HTTP\nstatus stays `200`.\n\nJSON-RPC errors:\n\n| Code | When |\n|---|---|\n| `-32700` | The body is not valid JSON (HTTP `400`). |\n| `-32600` | The body is not a JSON-RPC request object (HTTP `400`). |\n| `-32601` | Unknown method: `unsupported method: <method>`. |\n| `-32602` | `resources/read` with an unknown URI: `unknown resource: <uri>`. |\n| `-32003` | The tool exists but the caller may not use it. Messages: `tool not allowed for this API key: <name>`, `tool disabled on this server: <name>`, `API key lacks the \'write\' scope for tool: <name>`. |\n\nHTTP errors before JSON-RPC runs:\n\n| Status | When |\n|---|---|\n| `401` | No key, or a key that is unknown, disabled, deleted or replaced by a roll (`invalid API key`). Carries a `WWW-Authenticate` header that points OAuth clients at the protected resource metadata. |\n| `403` | The key lacks the `mcp` scope (`{"error":"API key lacks the \'mcp\' scope","required_scope":"mcp"}`), or a browser request failed the same-origin check. |\n| `405` | Any method other than `POST`. |\n| `409` | No vault is configured yet. |\n| `429` | Rate limit or cooldown after failed attempts. |\n\n## What each key sees\n\n`tools/list` is filtered per caller:\n\n- A tool switched off on the server is hidden for everyone.\n- A key whose tool list is not `"*"` only sees the tools in its list.\n- A key without the `write` scope only sees read-only tools.\n- Admin tools are added for keys with the `admin` scope (and for browser\n sessions).\n\n`tools/call` on a tool that `tools/list` would hide returns `-32003`. Details\nare in [Tool switches and per-key permissions](contracts/tools-permissions.md).\n\n### Privacy rules\n\nThe owner can hide notes and folders from specific agents (web UI,\n`/api/privacy`, or the `privacy_*` admin tools). For an API key covered by a\nrule, every tool works as if the hidden paths did not exist: they are left out\nof listings, search, the graph, tags, events, logs, locks and folder metadata; a\nhidden path named in an argument is answered as not found, for reads and writes\nalike; and folder operations that would carry hidden items along are refused.\nIf the rules cannot be read, the key sees nothing (fail closed). Browser\nsessions are never filtered.\n\n## Tools\n\nR = read-only (needs only the `mcp` scope). W = changes the vault or server\nstate (also needs the `write` scope). Unless marked required, arguments are\noptional. Paths are vault-relative, for example `Projects/Plan.md`.\n\n### Notes (`note`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_memory` | R | none | Every note grouped by folder: `{folder: [{path, name, folder, mtime}]}`. |\n| `read_memory` | R | `path` (string, required) | Markdown body, frontmatter, tags and backlinks of one note. |\n| `create_memory` | W | `title` (string, required), `folder` (string, default `Memory`; `Root` or empty for the top level), `content` (string; default is a stub with `created` frontmatter and a heading) | Creates `<folder>/<title>.md` and returns `{ok, path}`. |\n| `save_memory` | W | `path` (string, required), `content` (string, required) | Replaces the whole note. |\n| `patch_memory` | W | `path` (string, required), `ops` (array, required) | Partial edits. Each op is an object: `{op:"append", text}`, `{op:"prepend", text}`, `{op:"replace", find, with}`, `{op:"set_field", field, value}`, `{op:"add_tag", tag}`, `{op:"remove_tag", tag}`. |\n| `delete_memory` | W | `path` (string, required) | Deletes a note (recoverable from git history). |\n| `move_memory` | W | `path` (string, required), `folder` (string, required) | Moves a note into another folder. Wikilinks resolve by note name, so they keep working. |\n| `rename_memory` | W | `path` (string, required), `new_name` (string, required) | Renames a note in its folder. |\n\n### Search (`search`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_stats` | R | none | Counts of notes, links and folders. |\n| `search_memory` | R | `q` (string, required; `query` is accepted as an alias), `limit` (integer, default 12) | Search titles and bodies. Supports `tag:x` and `#x`. |\n\n### Query (`query`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `query_memory` | R | `folder`, `tags`, `author`, `type`, `status` (strings), `limit` (integer, default 50) | Filter notes by frontmatter. |\n| `find_similar` | R | `path` (string, required), `limit` (integer, default 8) | Notes most similar to one note (shared tags and words). |\n| `suggest_links` | R | `path` (string, required), `limit` (integer, default 8) | Similar notes not yet linked from this one. |\n| `list_tags` | R | none | Every tag with its usage count. |\n| `rename_tag` | W | `old` (string, required), `new` (string, required) | Renames a tag across the vault. |\n| `merge_tag` | W | `a` (string, required), `b` (string, required) | Merges tag `a` into tag `b` across every note. |\n\n### Tags (`tag`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_tags` | R | `path` (string; not in the advertised schema) | Every tag with its count, or the tags of one note when `path` is given. |\n| `search_by_tag` | R | `tag` (string, required), `limit` (integer, default 50; not in the advertised schema) | Every note carrying a tag. |\n| `add_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Adds tags to a note. A leading `#` is stripped. |\n| `remove_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Removes tags from a note. |\n| `set_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Replaces a note\'s tag list. |\n\n### Folders (`folder`, `ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_folders` | R | none | `{count, folders: [{name, count, color}]}`. |\n| `create_folder` | W | `name` (string, required) | Creates a folder. |\n| `rename_folder` | W | `folder` (string, required), `name` (string, required, one segment) | Renames a folder in place. Notes, sub folders, color and icon move along. |\n| `move_folder` | W | `folder` (string, required), `into` (string; empty or `Root` = top level) | Moves a folder with everything in it. |\n| `move_folder_contents` | W | `folder` (string, required), `into` (string; empty = top level) | Moves everything inside a folder into another folder, then removes the empty folder. Name clashes get a `-N` suffix. |\n| `delete_folder` | W | `folder` (string, required) | Deletes a folder. Its notes move to Root. |\n| `folder_stats` | R | `folder` (string, required) | Note count and metadata for one folder. |\n| `get_folder_meta` | R | `folder` (string) | Color, icon and description of one folder, or of every folder. |\n| `set_folder_meta` | W | `folder` (string, required), `color`, `icon`, `desc` (strings) | Sets folder display metadata. A field sent as an empty string is cleared. |\n\n### Graph (`graph`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_graph` | R | none | Whole graph: `{nodes: [{id, path, folder, color, degree, tags, mtime}], links: [{source, target}]}`. |\n| `get_neighbors` | R | `path` (string, required), `depth` (integer, default 1) | Notes within N hops. |\n| `get_subgraph` | R | `path` (string, required), `depth` (integer, default 1), `max_nodes` (integer, default 60) | Subgraph around one note. |\n| `find_path` | R | `source` (string, required), `target` (string, required) | Shortest wikilink path between two notes. |\n| `get_hubs` | R | `limit` (integer, default 10) | Most connected notes. |\n| `get_isolated` | R | none | Notes with no links in or out. |\n| `link_stats` | R | `path` (string, required) | Outgoing, incoming and unresolved links of one note. |\n| `broken_links` | R | none | Wikilinks pointing at notes that do not exist. |\n\n### Versioning (`version`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_history` | R | `path` (string, required), `limit` (integer, default 20) | Git history of a note. A single entry is returned as an object, several as an array. |\n| `get_note_at` | R | `path` (string, required), `rev` (string, required) | `{ok, path, rev, content}` at a revision. |\n| `diff` | R | `path` (string, required), `rev_a` (string, required), `rev_b` (string) | Diff between two revisions, or `rev_a` against the working tree. |\n| `restore_memory` | W | `path` (string, required), `rev` (string, required) | Restores a note to a revision. |\n| `snapshot` | W | `label` (string, required) | Tags the whole vault (git tag). |\n| `soft_delete` | W | `path` (string, required) | Moves a note to `.Trash`. |\n| `restore_trash` | W | `name` (string, required), `into` (string, default `Root`) | Restores a note from `.Trash` into a folder. |\n\n### Bulk writes (`write`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `batch_create` | W | `notes` (array, required) of `{title, folder (default Root), content}` | Creates many notes in one call. |\n| `duplicate_memory` | W | `path` (string, required) | Copies a note as `<name>-copy` in the same folder. |\n| `merge_memory` | W | `paths` (array of strings, required), `into` (string, required) | Merges several notes into one target note. |\n| `template_create` | W | `template` (string, required), `title` (string, required), `folder` (string, default `Root`), `variables` (object) | Creates a note from a file in `Templates/` with `{{var}}` substitution. |\n| `bulk_replace` | W | `find` (string, required), `replace` (string, required), `folder` (string), `regex` (boolean, default false), `dry_run` (boolean, default false) | Find and replace across notes. Needs `write` even with `dry_run`. |\n| `bulk_delete` | W | `paths` (array of strings), `folder` (string) | Deletes many notes by list or by folder. |\n\n### Collaboration (`collab`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `lock_node` | W | `path` (string, required), `owner` (string, default the caller), `ttl` (integer seconds, default 300) | Soft lock on a note. |\n| `release_lock` | W | `path` (string, required), `owner` (string, default the caller) | Releases a lock. |\n| `get_locks` | R | none | Active locks. |\n| `mention_agent` | W | `agent` (string, required), `path` (string, required), `message` (string) | Writes `> @agent: message` into a note. |\n| `get_assignments` | R | `agent` (string) | Notes with `assigned_to` in their frontmatter. |\n\n### Activity and health (`ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_events` | R | `since` (number, unix time), `folder`, `actor` (strings), `limit` (integer, default 50) | Recent note created, updated and deleted events. |\n| `presence` | R | `window` (integer seconds, default 300) | Agents active within the window. |\n| `get_logs` | R | `range` (string, default `1d`; also `7d`, `today`, `yesterday`), `actor` (string), `limit` (integer, default 100) | Activity log for a period. |\n| `search_logs` | R | `q` (string, required), `range` (string, default `7d`), `actor` (string), `limit` (integer, default 100) | Keyword search in the activity log. |\n| `digest` | R | `folder` (string), `since` (number) | Event counts per actor and per type. |\n| `healthcheck` | R | none | Note count, broken links, orphans and git status. |\n| `stale_detection` | R | `days` (integer, default 30) | Notes untouched for more than N days. |\n\n### Identity (`identity`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `set_my_name` | W | `name` (string, required) | Sets the display alias shown in the activity feed and log. |\n| `set_my_color` | W | `color` (string, required; `#rrggbb`, or `""` to reset) | Sets the calling API key\'s display color. Fails for browser sessions. |\n| `list_actors` | R | none | `{me, aliases}`: the caller and every known alias. |\n\n### Import and export (`interop`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `export_memory` | W | `paths` (array of strings, required; notes or folders), `out_path` (string) | Writes a zip of the given paths to the server\'s exchange folder and returns `{ok, path, name, bytes}`, where `path` and `name` are the zip\'s file name. `out_path` is a plain file name ending in `.zip` (letters, digits, `.`, `_`, `-`, at most 120 characters); the default is `memora-export-<time>.zip`. |\n| `import_memory` | W | `zip_path` (string, required), `overwrite` (boolean, default false) | Imports notes from a zip in the exchange folder, by the file name `export_memory` returned. |\n\nThe exchange folder is `memora-exchange` in the server\'s temporary directory.\nTools never read or write anywhere else on the server\'s disk.\n\n### Checks, to-dos and pins (`ux`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_todos` | R | `path` (string) | Open checklist items (`- [ ]`) in one note or the whole vault. |\n| `follow_ups` | R | none | Notes whose status is still awaiting action. |\n| `validate_memory` | R | `path` (string, required) | Checks frontmatter, created date, tags and links of a note. |\n| `list_pins` | R | none | The owner\'s pinned notes and folders in sidebar order: `{count, pins:[{kind, path, position, missing}]}`. `missing` is true when the path no longer exists (renamed or deleted outside Memora). |\n| `pin` | W | `path` (string, required), `kind` (`note` or `folder`; default: what the path is on disk), `position` (integer from 0; default: the end) | Pins an existing note or folder, or moves its pin. A note path may leave out `.md`. At most 200 pins. Returns the list. |\n| `unpin` | W | `path` (string, required), `kind` | Removes a pin; the note or folder is not touched. Returns the list with `removed`. |\n\nPins are shared by every browser of the owner (`/api/pins`). They follow their note or\nfolder through renames and moves done by Memora (over MCP or HTTP, including notes inside\na moved folder) and are removed when the item is deleted or moved to the trash; deleting a\nfolder removes every pin under it. A key whose privacy rules hide a path neither lists\nnor changes its pin, and `position` counts only the pins the key can see.\n\n### Admin tools (`admin`)\n\nListed and callable only for keys with the `admin` scope (and for browser\nsessions). They are not part of the switchable catalog: global tool switches and\na key\'s tool list do not apply to them, and they do not need `write`.\n\n| Tool | Arguments | Purpose |\n|---|---|---|\n| `admin_list_tools` | none | `{tools: [{name, category, description, enabled}]}` for every catalog tool. |\n| `admin_set_tool` | `name` (string, required), `enabled` (boolean, required) | Switches a catalog tool on or off for every key. Returns `{ok, name, enabled}`. |\n| `privacy_list` | `path` (string), `kind` (`node` or `folder`) | Without `path`: every privacy rule. With `path`: that note or folder\'s own rule, the folder rules it inherits, and which agents can see it. |\n| `privacy_set` | `path` (string, required), `agents` (array of key ids or names, required; a comma-separated string also works), `kind` (`node` or `folder`), `mode` (`deny` or `allow_only`, default `deny`) | Replaces the rule on a path. `deny` hides it from the listed agents; `allow_only` hides it from every other agent, including keys created later. `deny` with no agents removes the rule. A node rule follows its note through renames and moves. |\n| `privacy_clear` | `path` (string, required), `kind` (`node` or `folder`) | Removes the path\'s own rule. Rules on parent folders still apply. |\n\nWhen `kind` is omitted it is taken from the path on disk: a folder if a folder\nexists there, otherwise a note.\n\n## Identity and tracking\n\nEvery tool call is published to the web UI\'s realtime activity stream as an\n`ai_activity` start and end pair, named after the API key (or the signed-in\nuser), with the note paths involved. Calls are also counted per key: the Keys\npage and `GET /api/keys` show each key\'s `uses`, `last_ip`, and the tools it has\ncalled recently. `initialize` registers the connection under the key\'s name\n(`GET /api/aliases`). `set_my_name` changes the alias shown in the activity\nfeed and log, and `set_my_color` changes the key\'s color in the UI. See\n[API.md](API.md) for the HTTP endpoints.\n',zN='# HTTP API\n\nThe `memora` binary serves the HTTP API, the MCP endpoint, the OAuth endpoints,\nthe web UI, and the WebSocket on one port. This document lists the HTTP endpoints.\n\n## Authentication\n\nThe Auth column in the tables below uses these levels:\n\n- None: reachable without credentials.\n- Session: requires the `memora_sess` cookie set by a successful login.\n- Key (`scope`): an API key sent as `Authorization: Bearer <key>` or `X-API-Key: <key>`\n that carries the named scope.\n- Session or key (`scope`): either of the above.\n- Session only: an API key is not enough. API keys get `401` (or `403` where noted).\n- +CSRF: the same-origin check described below applies.\n\n### API key scopes\n\nA key carries any of the scopes `mcp`, `read`, `write`, and `admin`. New keys get\n`mcp`, `read`, and `write` unless other scopes are requested. The scope a route\nneeds is decided by its path and method:\n\n| Scope | Routes |\n|---|---|\n| `mcp` | `/mcp` |\n| `admin` | `/api/tools`, `/api/keys` and `/api/keys/*`, `/api/access` and `/api/access/*`, `/api/logs/settings`, `/api/oauth/clients` and `/api/oauth/clients/*`, `/api/privacy` and `/api/privacy/*` |\n| `read` | Every other `GET` or `HEAD` under `/api/` |\n| `write` | Every other method under `/api/` |\n\nA key without the needed scope gets `403 {error, required_scope}`. A missing key\ngets `401`; for `/mcp` the `401` carries a `WWW-Authenticate` header,\n`Bearer resource_metadata="<base>/.well-known/oauth-protected-resource"`, so OAuth\ncapable clients can start sign-in. An invalid key gets `401` and is logged; an\nIP that keeps presenting invalid keys is put on a cooldown (`429`).\n\n`/api/auth/*` never accepts an API key: without a valid session it answers `401`.\n\nAPI keys see the vault through their privacy rules (see [Privacy](#privacy)):\nnotes and folders hidden from a key behave as if they do not exist. A browser\nsession sees everything.\n\n### CSRF\n\nWrite endpoints that accept a session check the request origin whenever a\nsession cookie is present: `Origin` (or, without it, `Referer`) must match the\nrequest `Host` (or an `X-Forwarded-Host` sent by a trusted proxy), and\n`Sec-Fetch-Site: cross-site` is refused. A failed check is\n`403 {"error":"origin mismatch"}`. Requests without a session cookie (API-key\nclients) pass, since a browser cannot attach an API key on its own.\n\nThe public auth forms (`/api/auth/login`, `/api/auth/verify`,\n`/api/auth/bootstrap`, `/api/auth/reset`) also refuse a foreign or `null`\n`Origin` when no cookie exists yet. A request with neither `Origin` nor\n`Referer` (curl, the CLI) passes.\n\n### Locked instance\n\nWhile the instance is LOCKED, `/api/*` and `/mcp` answer\n`423 {error, locked: true, hint}` except for `/api/auth/state`, `/api/auth/verify`,\n`/api/auth/login`, `/api/auth/logout`, `/api/auth/bootstrap`, and\n`/api/auth/reset`. Other pages redirect to `/login?locked=1`; static assets,\n`/login`, `/logout`, `/healthz`, and `/favicon.ico` are still served.\n`/api/auth/login` itself answers `423` while locked.\n\n### Vault not configured\n\nUntil a vault folder is configured, `/mcp` and every `/api/*` route except\n`/api/auth/*`, `/api/settings*`, `/api/config`, `/api/keys*`, `/api/tools`,\n`/api/access*`, and `/api/ui/*` answer\n`409 {"error":"vault not configured", "needs_vault":true}`.\n\n### Limits and other gates\n\n- Requests for a host outside the configured domain list get a bare `404`.\n- Access rules (see `/api/access`) can block a caller:\n `403 {"error":"access denied by stack rule", ip}`.\n- Per-IP rate limits answer `429` with a `Retry-After` header and\n `{error, limited, cooldown, retry_after}`. Login, code check, setup, reset, profile,\n password, and username changes have a stricter limit and a cooldown after\n repeated failed attempts. Requests from the machine itself and `/healthz` are\n not limited.\n- A request that takes longer than 30 seconds is answered with `408`.\n- A password hashing pool that is busy answers `503` with `Retry-After: 2`.\n\nResponses are JSON unless stated otherwise. Errors are `{"error": "..."}`. Vault\nerrors map to `404` for not-found (including paths hidden from the caller) and\n`400` for bad input.\n\n## Health and discovery\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/healthz` | None | `{ok, server}` for unauthenticated callers from other machines. A signed-in browser or a caller on the same machine gets `{ok, server, version, vault_configured, vault, armed, locked, base_url, base_url_configured}`. |\n| GET | `/.well-known/mcp.json` | None | The MCP discovery card: `{name, version, description, mcp, auth, capabilities, tools, resources}`. `tools` lists the full catalog with `enabled` per tool. |\n| GET | `/tools` | None | An HTML rendering of the tool catalog. A signed-in browser gets the app shell instead. |\n| POST | `/mcp` | Key (`mcp`), or Session (+CSRF) | MCP over streamable HTTP (JSON-RPC in, JSON-RPC out). See [MCP.md](MCP.md). A session has full access; a key is limited by its tool grant. Notifications get `202` with no body. Malformed JSON is `400` with a JSON-RPC error. Other methods get `405` with `Allow: POST`. |\n\n## Auth\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/auth/state` | None | `{bootstrap, realm, min_password_len, gateway, armed, locked, setup_hint, ready, checks:{vault, state}, code_required, cooldown, vault_configured}`. Adds `signed_out` (`password_changed` or `signed_out_remotely`) when the browser\'s session was ended on purpose, and `mode`, `expires_in`, `ttl` while a setup or reset window is open. |\n| POST | `/api/auth/verify` | None (+CSRF) | Checks the setup code shown on the server before the setup or reset form is shown. Body: `{code}`. Returns `{ok, mode, expires_in, user}`. `403` when no window is open or the instance is not ready. A wrong code closes the window and voids the code: `403 {error, burned:true}`. |\n| POST | `/api/auth/login` | None (+CSRF) | `{ok, user, expires_in, redirect}` and sets the session cookie. Body: `{username, password}`. `400` when a field is missing, `401` on bad credentials, `403` if the account is disabled, `423` if locked, `429` during a cooldown. |\n| POST | `/api/auth/logout` | None (+CSRF) | `{ok:true}`. Ends the session named by the cookie, if any, and clears the cookie. |\n| POST | `/api/auth/bootstrap` | None (+CSRF) | Creates the owner account. Body: `{code, username, password}`. Returns `{ok, user, redirect, persisted}` and sets a session cookie. The username is stored lowercase. `400` for an invalid username or password length; `403` unless a window is open, the code is right, the instance is ready, and no account exists. |\n| POST | `/api/auth/reset` | None (+CSRF) | Sets a new password for the single account, and may rename it. Body: `{code, username, password}`. Returns `{ok, user, persisted}`. Signs out every session. `400` for invalid input; `403` unless a window is open, the code is right, and an account exists. |\n| POST | `/api/auth/profile` | Session only (+CSRF) | With `password` in the body, changes the password exactly like `POST /api/settings/password` (body `{current, password, confirm}`). Otherwise sets `display_name` (at most 48 characters) and returns `{ok, changed, persisted, user, password_changed:false}`; with no `display_name` it returns `{ok, changed:false}`. |\n| GET | `/api/auth/me` | Session only | `{authenticated, user, enabled, expires_in}`. `401` without a session. |\n| GET | `/api/auth/events` | Session only | Recent entries of the security activity log, newest first: `{events:[{at, event, ip, user, detail, actor, actor_kind, actor_id}], count}`. `user` is the stored actor (`key:<id>` for API-key calls); `actor` is the display name (the key\'s current name, falling back to its id; the username for the browser), `actor_kind` is `agent` or `user` (null when there is no actor). Query: `limit` (default 200, max 2000), `q`. |\n\n## Pages\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/login` | None | The sign-in page. A signed-in browser is redirected to `/` unless the instance is locked or the query has `oauth` (the OAuth consent card). |\n| any | `/logout` | None | Ends the session, clears the cookie, and redirects to `/login`. A cross-site request only clears the cookie. |\n| GET | `/`, `/index.html` | Session | The web app shell. Without a session: `302` to `/login`. `503` when the UI assets are not installed. |\n| GET | App routes (see below) | Session | The same app shell as `/`. Without a session: `302` to `/login?r=<path>`, so sign-in returns to the page. |\n\nApp routes are the web app\'s client-side pages: `/brain`, `/nodes`, `/graph`,\n`/canvas`, `/tags`, `/activity`, `/agents`, `/access`, `/settings`,\n`/overview`, `/welcome`, the older names `/home`, `/vault`, `/logs`, `/keys`,\nand `/node/` or `/node/<percent-encoded vault path>`. The path is never used to\nread a file; a path holding NUL or another control character (raw or\npercent-encoded) is `400`. `/tools` is an app route for a signed-in browser and\nthe public tool catalog otherwise.\n\nHTML pages are sent with `Cache-Control: no-cache, no-store, must-revalidate`\nand a per-response CSP nonce.\n\nAny other `GET` that asks for HTML (`Accept: text/html`), is outside `/api/`,\n`/mcp`, `/oauth`, and `/.well-known`, and has no file extension in its last\nsegment gets the app shell (which shows its "page not found" view). Every other\nunmatched request is `404 {"error":"not found"}`.\n\n## Static assets\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/assets/{name}` | None | Static UI assets (whitelisted filenames only, else `404`). |\n| GET | `/app.js`, `/app.css`, `/login.css` | None | The UI bundle and styles. Revalidated on every load (`Cache-Control: no-cache`, ETag). |\n| GET | `/favicon.svg` | None | The icon. |\n| GET | `/favicon.ico` | None | `204` with no body. |\n| GET | `/manifest.webmanifest`, `/sw.js`, `/robots.txt`, `/offline.html`, `/icon-192.png`, `/icon-512.png`, `/icon-maskable-512.png`, `/apple-touch-icon.png` | None | PWA files and `robots.txt`. Images and the manifest are cached for 5 minutes; code is revalidated on every load. |\n\n## Vault\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/tree` | Session or key (`read`) | Notes grouped by folder. |\n| GET | `/api/note` | Session or key (`read`) | `{path, name, content, html, tags, frontmatter, backlinks, size, mtime}`. Query: `path` (`400` when empty). |\n| GET | `/api/vault/file` | Session or key (`read`) | The raw bytes of one image file in the vault (PNG, JPEG, GIF, WebP, AVIF, BMP, ICO; never SVG). Query: `path` (vault-relative). The file content must match its type. At most 10 MiB (`413`). Sent with an `ETag` (`304` on `If-None-Match`), `Cache-Control: private, max-age=300`, and a sandbox CSP. `400` invalid path, `403` path not allowed, `404` not found, `415` not an image. |\n| GET | `/api/folder-meta` | Session or key (`read`) | Folder metadata keyed by folder name. Query: `folder` (optional). |\n| POST | `/api/save` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{path, content}`. Overwrites the note. |\n| POST | `/api/create` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{title, folder?, content?}`. |\n| POST | `/api/rename` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, name}`. |\n| POST | `/api/move` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, folder?}`. |\n| POST | `/api/delete` | Session or key (`write`, +CSRF) | `{ok:true}`. Body: `{path}`. |\n| POST | `/api/folder` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{name}`. |\n| POST | `/api/folder/rename` | Session or key (`write`, +CSRF) | `{ok, from, to, notes}`. Body: `{folder, name}`. |\n| POST | `/api/folder/move` | Session or key (`write`, +CSRF) | Moves a folder and everything in it. `{ok, from, to, notes}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/folder/move-contents` | Session or key (`write`, +CSRF) | Moves everything inside a folder into another one, then removes the emptied folder. Name clashes get a `-N` suffix. `{ok, from, to, moved}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/delete-folder` | Session or key (`write`, +CSRF) | Deletes a folder and moves its notes to the top level. `{ok, deleted_folder, moved_to_root}` where `moved_to_root` lists the new note paths. Body: `{folder}`. |\n| POST | `/api/folder-meta` | Session or key (`write`, +CSRF) | `{ok, folder}`. Body: `{folder, color?, icon?, desc?}`. |\n\nThe three folder operations also publish a `folder_changed` realtime event so\nopen browsers reload their tree.\n\n## Search and graph\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/search` | Session or key (`read`) | `{q, count, hits:[{path, name, folder, score, snippet}]}`, at most 20 hits. Query: `q`. Supports `tag:x` and `#x`. |\n| GET | `/api/stats` | Session or key (`read`) | `{notes, links, folders}`. |\n| GET | `/api/graph` | Session or key (`read`) | `{nodes:[{id, path, folder, color, degree, tags}], links:[{source, target}]}`. `tags` holds inline `#tags` plus frontmatter `tags` (as the note view reports them). Realtime `node_*` events\' `node` payload carries `tags` too. |\n| GET | `/api/aliases` | Session or key (`read`) | `{aliases:[{alias, key_id, key_name, first_seen, last_seen, connections, actor, actor_kind}]}`: one record per API key that sent MCP `initialize`, kept in memory until the server restarts. `key_name` and `actor` are the key\'s current name (fallback: the id). |\n| GET | `/api/actors` | Session or key (`read`) | `{actors:[{actor, alias, display, events, tools, last_ip, last_ts, seen_minutes_ago}], count}`. `seen_minutes_ago` is `-1` when the actor has no events. |\n\n## Privacy\n\nPrivacy rules hide notes or folders from chosen agents (API keys). A rule has a\n`kind` (`node` or `folder`), a `path`, a `mode` (`deny`: hidden from the listed\nkeys; `allow_only`: hidden from every key except the listed ones), and a list\nof keys. Folder rules apply to everything inside the folder.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/privacy` | Session or key (`admin`) | `{count, rules:[{id, kind, path, mode, keys:[{id, name, color}], created_at, updated_at}], agents:[{id, name, color, enabled}]}`. |\n| GET | `/api/privacy/path` | Session or key (`admin`) | The privacy state of one path: `{path, kind, own, own_rules, inherited, agents:[{id, name, color, enabled, can_see, hidden_by}], private}`. `own` is `{mode, keys}` or `null`. Query: `path`, `kind` (optional; defaults to `folder` when the path is a folder on disk, else `node`). |\n| PUT | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Replaces the rule on a path. Body: `{path, kind?, mode, keys}`. `mode` defaults to `deny`; `keys` is a list of key ids (or unique key names). `deny` with no keys removes the rule. Returns the same shape as `GET`. |\n| DELETE | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Removes the rule on a path. Query: `path`, `kind` (optional). Returns the same shape as `GET`. |\n\nChanges are written to the activity log and publish a `privacy_changed`\nrealtime event.\n\n## API keys, tools, and access\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/keys` | Session or key (`admin`) | `{count, keys:[{id, name, enabled, scopes, tools, prefix, created, color, revealable, uses, last_ip, used_tools}]}`. `tools` is `"*"` or a list of tool names; `revealable` says whether the secret can be shown again; `used_tools` lists recently used tools and routes. |\n| POST | `/api/keys` | Session or key (`admin`, +CSRF) | Creates a key. Body: `{name?, tools?, scopes?, color?}`. `tools` is `"*"` or a list of tool names; `scopes` a list of scope names (an empty list means the defaults). Returns `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. `400` for an unknown tool or scope. |\n| POST | `/api/keys/roll` | Session or key (`admin`, +CSRF) | New secret for an existing id. Body: `{id}`. Returns `{ok, id, key, prefix, persisted}`. `404` for an unknown id. |\n| POST | `/api/keys/reveal` | Session only (+CSRF) | Shows the secret of a key created or rolled from the dashboard again. Body: `{id, current}` where `current` is the owner\'s password. Returns `{ok, id, key}`. `403` for a wrong password; `429` after 5 wrong passwords (5 minute pause); `404 {error:"not_stored", message}` when the secret is not stored (for example keys created by the CLI or by OAuth). |\n| POST | `/api/keys/update` | Session or key (`admin`, +CSRF) | Body: `{id, name?, enabled?, tools?, scopes?, color?}`. `color` as `""` or `null` clears it. Returns `{ok, id, name, enabled, color, tools, scopes, persisted}`. `400` for an unknown tool or scope, `404` for an unknown id. |\n| POST | `/api/keys/delete` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Moves the key to the trash. Body: `{id}`. |\n| POST | `/api/keys/restore` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Restores a deleted key. Body: `{id}`. `404` when no deleted key has that id. |\n| GET | `/api/tools` | Session or key (`admin`) | `{tools:[{name, category, description, enabled}]}`: the MCP tool catalog with the global on/off switch of each tool. |\n| POST | `/api/tools` | Session or key (`admin`, +CSRF) | Switches a tool on or off for every caller. Body: `{name, enabled}`. Returns `{ok, name, enabled}`. `400` for an unknown tool. |\n| GET | `/api/access` | Session or key (`admin`) | `{default_allow, rules, count}`. |\n| POST | `/api/access/test` | Session or key (`admin`) | `{action, would_lock_out_caller}` for the given address or domain. Body: `{ip?, domain?}`. |\n| POST | `/api/access/rules` | Session or key (`admin`, +CSRF) | `{ok, count, persisted}`. Body: `{op, kind, value, action}`. `op` is `add` (default) or `remove`. `kind` is `ip`, `range`, `cidr`, `domain`, or `all`; `value` is required unless `kind` is `all`. `action` is `allow` or `block` (default `block`). `remove` deletes every rule matching the given `kind` and `value`; `404` when none match. |\n| GET | `/api/config` | Session or key (`read`) | `{realm, min_password_len, session_ttl, vault, version, gateway, update}`. `update` is the cached release check: `{current, latest, available, url, checked_at, state}`, `state` one of `ok`, `none` (no release published), `error`, `disabled`, `pending`. |\n\n## Settings\n\nAll settings endpoints need a signed-in browser.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/settings` | Session only | `{user, vault_configured, vault, vault_suggested, vault_writable, stats, min_password_len, expires_in, session_ttl, session_max_age, state_dir}`. `stats` is `{notes, links, folders}` or `null` without a vault. |\n| POST | `/api/settings/password` | Session only (+CSRF) | Body: `{current, password, confirm}`. Returns `{ok, user, password_changed, revoked_sessions, persisted}`. Every other session is signed out. `400` for a short, mismatched, or unchanged password; `403` for a wrong current password (counts toward the login cooldown). |\n| POST | `/api/settings/username` | Session only (+CSRF) | Renames the account. Body: `{username, current}`. Returns `{ok, user, changed}` (plus `persisted` when changed). The username is stored lowercase. Sessions stay signed in. `400` for an invalid username, `403` for a wrong password. |\n| POST | `/api/settings/vault` | Session only (+CSRF) | Sets the vault folder and switches the running server to it. Body: `{path, create?}`. `path` must be absolute, without `..`, writable, not a system folder, and not overlap the state folder; with `create` a missing folder is created (its parent must exist). Returns `{ok, vault, created, stats}`. `400` with a message when the folder is refused. |\n| GET | `/api/settings/sessions` | Session only | `{sessions:[{id, current, source, alias, ip, user_agent, created_at, last_seen, expires_in}], count}`: live browser sessions. API keys are not sessions and never appear here. |\n| POST | `/api/settings/sessions/revoke` | Session only (+CSRF) | Signs other browsers out. Body: `{id}` or `{others:true}`. Returns `{ok, revoked}`. `400` for the current session (use logout), `404` when the session has already ended. |\n| POST | `/api/settings/sessions/rename` | Session only (+CSRF) | Names a device. Body: `{id, alias}`; an empty alias clears it. Returns `{ok, alias}`. |\n| GET | `/api/settings/sessions/activity` | Session only | `{events, count, ip, since}`: activity log entries from that session\'s IP address since it signed in, API-key entries left out, newest first, at most 200. Query: `id`. |\n\nSession `id` values are the short ids returned by `GET /api/settings/sessions`\n(a unique prefix also works). An ambiguous or malformed id is `400`.\n\n## OAuth\n\nMemora is an OAuth 2.1 authorization server for remote MCP clients. Only the\nauthorization code flow with PKCE (`S256`) is supported. The access token is a\nnew API key named after the client, with the default scopes (`mcp`, `read`,\n`write`) and every tool; it appears on the Agents page like any other key and\nis revoked by deleting or disabling that key. URLs in the metadata use\n`MEMORA_BASE_URL` when it is set, else the scheme and host of the request.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/.well-known/oauth-protected-resource`, `/.well-known/oauth-protected-resource/mcp` | None | Protected resource metadata (RFC 9728): `{resource, authorization_servers, bearer_methods_supported, scopes_supported, resource_name}`. |\n| GET | `/.well-known/oauth-authorization-server`, `/.well-known/oauth-authorization-server/mcp`, `/.well-known/openid-configuration` | None | Authorization server metadata (RFC 8414): `issuer`, the authorization, token, and registration endpoints, supported response types (`code`), grant types (`authorization_code`, `refresh_token`), PKCE methods (`S256`), token endpoint auth methods, `scopes_supported` (`mcp`), and `client_id_metadata_document_supported: true`. |\n| POST | `/oauth/register` | None | Dynamic client registration (RFC 7591). Body: `{redirect_uris, client_name?}`. `redirect_uris` holds 1 to 10 URIs, each HTTPS or plain HTTP on `localhost`, `127.0.0.1`, or `[::1]`, without a fragment. Returns `201 {client_id, client_name, redirect_uris, client_id_issued_at, token_endpoint_auth_method, grant_types, response_types}`. `400 {error, error_description}` for invalid metadata. |\n| GET | `/oauth/authorize` | None | `302` to `/login?oauth=1&<query>`, where the sign-in page shows a consent card (after sign-in when needed). |\n| POST | `/oauth/token` | None | Form-encoded or JSON body. `grant_type=authorization_code` with `code`, `code_verifier`, `client_id` (or HTTP Basic), and optional `redirect_uri`; or `grant_type=refresh_token` with `refresh_token` and optional `client_id`. Returns `{access_token, token_type:"Bearer", refresh_token, scope:"mcp"}`. Codes are single use and expire after 10 minutes. A refresh gives the same key a new secret and a new refresh token. Errors are `400 {error, error_description}` (`invalid_request`, `invalid_grant`, `unsupported_grant_type`). |\n| GET | `/api/oauth/request` | None | What the consent card shows for an authorization request. Query: the `/oauth/authorize` query. Returns `{ok:true, client:{id, name, kind}, redirect_host, signed_in, user}` or `{ok:false, error, error_description, redirect}`. |\n| POST | `/api/oauth/approve` | Session only (+CSRF) | Body: `{query, allow}` where `query` is the authorization request query. Returns `{ok:true, redirect}`: the client\'s redirect URI with a `code` when `allow` is `true`, else with `error=access_denied`. An invalid request returns `{ok:false, error, error_description, redirect}`. `401` without a session. |\n| GET | `/api/oauth/clients` | Session or key (`admin`) | `{clients:[{client_id, name, redirect_uris, kind, created_at, fetched_at}], connections:[{key_id, client_id}]}`. `kind` is `dcr` (registered), `cimd` (metadata document), or `manual` (added by the owner). |\n| POST | `/api/oauth/clients` | Session or key (`admin`, +CSRF) | Registers a client by hand. Body: `{name?, redirect_uris}`. Returns `{ok, client}`. `400` for invalid redirect URIs. |\n| POST | `/api/oauth/clients/delete` | Session or key (`admin`, +CSRF) | Forgets a client and its refresh tokens. Body: `{client_id}`. Returns `{ok, deleted}`. Keys issued to the client stay until they are deleted. |\n\nA `client_id` may also be an HTTPS URL of a client metadata document. The\nserver fetches it (public addresses only, no redirects, at most 64 KiB), checks\nthat its `client_id` matches the URL, and caches it for 24 hours.\n\n## Logs and activity\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/logs` | Session or key (`read`) | `{range, count, events}`, newest first, each event with a local `time`. Query: `range` (for example `1d`, `7d`, `today`, `yesterday`, `all`; default `1d`), `days` (used when `range` is absent, at most 7), `since` and `until` (unix seconds; override `range`), `limit` (default 400, max 2000), `actor`, `q`. |\n| GET | `/api/logs/settings` | Session or key (`admin`) | `{max_mb, max_days, stats:{bytes, lines, oldest, newest, max_bytes, max_days}}` for the vault event log. |\n| POST | `/api/logs/settings` | Session or key (`admin`, +CSRF) | Body: `{max_mb?, max_days?}` (1 to 512 MB; 0 to 3650 days, 0 meaning no age limit). Returns the same shape as `GET`. The log is trimmed to the new limits at once. `400` for out-of-range values. |\n| GET | `/api/events` | Session or key (`read`) | `{events, count}`: the vault event log (`.events.jsonl`), oldest first, the newest `limit` entries. Query: `since` (unix seconds), `folder`, `actor` (the key name for agents), `limit` (default 100, max 2000). |\n\n### Realtime\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/ws` | Session only | WebSocket upgrade. The `Origin` must be same-origin (`403` otherwise). `503` when too many clients are connected. |\n| POST | `/_bus` | Loopback only | Publishes a JSON object (at most 64 KiB) into the event stream. Returns `{ok:true}`. `403` for callers that are not on the same machine or that come through a proxy (any forwarding header), `400` for a body that is not a JSON object, `413` for a body or event that is too large. |\n\nOn connect the server sends a `hello` event with the client count, replays the\nlast 40 stored events (each marked `replay: true`), then streams live events.\nWhen a client leaves, the others get a `presence` event with the new count.\nMessages from the client are ignored; the server pings every 30 seconds and\ncloses a connection that has been silent for 75 seconds.\n\n### `ai_activity` events\n\nEvery MCP `tools/call` publishes a `start` and an `end` event sharing `call_id`:\n\n```json\n{"type":"ai_activity","phase":"start","call_id":"c1a2b3c4d5e6-0","actor":"research-bot",\n "actor_kind":"agent","actor_id":"k_1a2b3c4d","action":"read_memory","label":"Plan/Index.md",\n "paths":["Plan/Index.md"],"_ts":1760600000.12}\n{"type":"ai_activity","phase":"end","call_id":"c1a2b3c4d5e6-0","actor":"research-bot",\n "actor_kind":"agent","actor_id":"k_1a2b3c4d","action":"read_memory","label":"Plan/Index.md",\n "paths":["Plan/Index.md"],"ok":true,"ms":2,"_ts":1760600000.12}\n```\n\n- `actor`: the API key\'s name (fallback: key id) with `actor_kind: "agent"`; for a\n browser session the username with `actor_kind: "user"`. `actor_id` is the key id (or\n the username). Node events (`node_created`, ...) from the call carry the same `actor`.\n- `action`: the tool name.\n- `paths`: vault-relative note paths from the arguments (`path`, `paths`, `from`, `to`,\n `old_path`, `new_path`, `into` of `merge_memory`, `source`/`target` of `find_path`)\n plus note paths found in the result (search hits, the created or moved note), at\n most 20, each at most 512 bytes (longer paths are dropped). Whole-vault overviews\n (`get_graph`, `list_memory`, logs, ...) add no result paths.\n- Read-only tools publish `start` after running (so it carries the result paths),\n immediately followed by `end`; mutating tools publish `start` before running and `end`\n after, with the result paths added.\n- `end` adds `ok`, `ms`, and on failure `error` (at most 200 characters). `label` is at\n most 160 characters. `_ts` is the publish time in unix seconds. `end` events are\n realtime only: they are not written to `.events.jsonl` or the replay buffer.\n\n## UI layout\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/ui/layout/{name}` | Session only | `{name, data, updated_at}`; `data` and `updated_at` are `null` if never saved. |\n| PUT | `/api/ui/layout/{name}` | Session only (+CSRF) | `{ok:true, updated_at}`. Body: `{data: <any JSON>}`. |\n\n`name` is `[a-z0-9_-]{1,40}` (else `400`). API keys get `403`. `data` is stored as\nserialized JSON of at most 512 KiB (`413` above); the request body limit is 600 KiB.\nLayouts are stored in the `ui_layout` table of `memora.db`. The web UI uses them for\n`canvas` (card positions and frames) and `graph` (pinned positions).\n\n## Pins\n\nThe owner\'s pinned notes and folders (the sidebar\'s Pinned list), shared by every\nbrowser and device of the instance.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/pins` | Session only | `{count, pins:[{kind, path, position, missing}]}` in display order. |\n| PUT | `/api/pins` | Session only (+CSRF) | Same as GET. Body: `{pins:[{kind, path}]}`, the whole ordered list (reorder, remove). |\n| POST | `/api/pins/pin` | Session only (+CSRF) | Same as GET. Body: `{kind, path, position?}`. Pins an existing note or folder at `position` (default: the end), or moves its pin there; `404` if it does not exist. |\n| POST | `/api/pins/unpin` | Session only (+CSRF) | Same as GET plus `removed`. Body: `{kind, path}`. |\n\n`kind` is `note` or `folder`. `path` is vault-relative as the tree shows it (notes end in\n`.md`): absolute paths, `..`, empty or hidden segments, `\\`, control characters and paths\nover 1024 characters get `400`, as do more than 200 pins. API keys get `403` (agents use\nthe MCP tools `list_pins`, `pin` and `unpin`). Bodies are limited to 256 KiB for `PUT`\nand 8 KiB for `pin`/`unpin` (`413`). `missing` is true when the path no longer exists,\nfor example after a rename outside Memora; such a pin is kept until it is removed.\n\nRenames, moves and deletes done by Memora (HTTP or MCP) rewrite or drop pins in the same\ndatabase transaction, including pins on notes and folders inside a moved folder;\nmoving an item to the trash or deleting it removes its pin, and deleting a folder\nremoves every pin under it. Every change publishes a `pins_changed` realtime event with\nno other data; open browsers reload the list. Pins are stored in the `pin` table of\n`memora.db`.\n\n## Status codes\n\n| Code | Meaning |\n|---|---|\n| 200 | Success. |\n| 201 | OAuth client registered. |\n| 202 | MCP notification accepted. |\n| 204 | `/favicon.ico`. |\n| 302 | Redirect (pages to `/login` without a session, `/login` to `/` when signed in, logout to `/login`, locked instance to `/login?locked=1`, `/oauth/authorize` to the consent page). |\n| 304 | Not modified (`/api/vault/file`, static assets). |\n| 400 | Bad request, for example a missing required field or an invalid value. |\n| 401 | Missing or invalid credentials, or a session-only endpoint called without a session. |\n| 403 | Blocked by an access rule, a CSRF origin mismatch, a missing key scope, a wrong password or setup code, or an endpoint that needs an open setup or reset window. |\n| 404 | Note, key, session, rule, or route not found; also any request for a host outside the domain list. |\n| 405 | `/mcp` called with a method other than `POST`. |\n| 408 | The request took longer than 30 seconds. |\n| 409 | No vault configured (`needs_vault: true`), or a state conflict. |\n| 413 | Body, layout, image, or event too large. |\n| 415 | `/api/vault/file` path is not an image. |\n| 423 | Instance is LOCKED. |\n| 429 | Rate limit or failed-attempt cooldown (`Retry-After` header). |\n| 500 | Internal error, for example the state database failed. |\n| 503 | UI assets are not installed, the password hashing pool is busy, or too many realtime clients. |\n',ON=`# Deployment
9636
9684
 
9637
9685
  This guide covers health checks, running Memora behind a reverse proxy, in a
9638
9686
  container, and under systemd, first-run and recovery, backups, and upgrades.
@@ -9925,7 +9973,7 @@ docker compose pull && docker compose up -d
9925
9973
 
9926
9974
  The server migrates \`memora.db\` on start. Take a \`memora-cli db backup\` first:
9927
9975
  a database migrated by a newer release cannot be opened by an older one.
9928
- `,UN="# Architecture\n\nThis document describes how Memora is put together: the crates, what each one\nowns, the request path from a browser or an agent to the vault, the realtime\nWebSocket fan-out, the auth model, and the storage model. Every claim here maps\nto code under `crates/`.\n\n## Crate layout\n\nMemora is a Cargo workspace with six crates. The web UI is a TypeScript app in\n`web/src`, built with Vite into `crates/http/assets`.\n\n| Crate | Binary | Owns |\n|---|---|---|\n| `memora-core` | (library) | The vault: walking notes, parsing wikilinks and frontmatter, the SQLite search index, search, the graph, git versioning, per-caller path visibility, and the `*_impl` methods that every interface calls. Also the realtime event hub. |\n| `memora-gateway` | (library) | Auth primitives: argon2id password hashing, API key generation and hashing, OAuth token and PKCE helpers, setup codes, the access stack evaluator, host and lock allow lists, scopes and per-key tool permissions, and reading the provisioning environment. No state of its own. |\n| `memora-state` | (library) | The state database `memora.db` (SQLite, WAL): opening, migrations, change detection, and one typed repository per table group (owner, settings, `server_config`, keys, tools, usage, sessions, arm window, access rules, activity, control requests, OAuth, privacy rules, UI layouts, retention), plus the one-time import of JSON state files. No SQL lives outside this crate. |\n| `memora-mcp` | (library) | The MCP server: the tool catalog, JSON-RPC 2.0 handling, the discovery card, client detection, `ai_activity` events, and the privacy view applied to agent callers. |\n| `memora-http` | `memora` | The axum server: routing, middleware, the REST API, OAuth 2.1 endpoints, the privacy API, the WebSocket and intake bus, sealed key copies, and serving the UI assets. |\n| `memora-cli` | `memora-cli` | The operator console (slash commands such as `/guide`, `/web`, `/keys`, `/tools`, `/sessions`, `/config`, `/backup`, `/db`, `/update`) and one-shot commands (`setup`, `reset-password`, `status`, `disarm`, `unlock`, `list`, `clear-cooldowns`, `vault`, `db ...`, `update`, `version`). It opens `memora.db` directly; run as root, it does database work as the state directory's owner. |\n\nDependencies point one way: `http` depends on `core`, `mcp`, `gateway`, and\n`state`; `mcp` depends on `core`, `gateway`, and `state`; `cli` depends on\n`gateway`, `mcp`, and `state`. `core`, `gateway`, and `state` depend on no\nother Memora crate.\n\n## What each crate owns\n\n### memora-core\n\n`MemoryStore` is the single point through which the vault is read and written.\nBoth the HTTP API and the MCP tools call its `*_impl` methods, so a change made\nthrough the UI and one made through an agent take the same code path.\n\n- `walk()` enumerates `.md` files under the vault root, skipping dot\n directories. Walk order is stable, so tools that depend on first-hit order\n behave deterministically.\n- Parsing: wikilinks, inline tags, frontmatter tags, and frontmatter fields.\n- The search index: a SQLite database at `<vault>/.fts.db`. It is derived data\n and is rebuilt when missing.\n- `search()` blends word matching over name and body with `tag:` and `#tag`\n filters, scored by hits, name hits, phrase, and position.\n- The graph: nodes are notes, links are resolved wikilinks.\n- Versioning: vault changes are committed to git (`create:`, `edit:`,\n `rename:`, `move:`, `delete:`, `folder:`); history, diff, restore, and\n snapshot read from that history.\n- Privacy views: while a caller's `PathView` is set, listings skip hidden\n notes, hidden paths resolve as \"not found\", and folder operations that would\n carry hidden items along are refused. A path hook reports renames, moves, and\n deletes so privacy rules follow the notes they protect.\n- The event hub (see below).\n\n### memora-gateway\n\n- `hash_password` and `verify_password` use argon2id.\n- `generate_key` produces `memora_live_` plus 128 random bits as hex.\n `hash_api_key` stores the SHA-256 hex of the key. `verify_key` compares in\n constant time.\n- `AccessStack` evaluates ordered IP, range, CIDR, domain, and catch-all rules.\n Loopback is always allowed.\n- `host_allowed` checks the `Host` against `MEMORA_DOMAIN` and the host of\n `MEMORA_BASE_URL`.\n- `tool_access` combines a key's scopes (`mcp`, `read`, `write`, `admin`), its\n tool list, and the global tool switches.\n\n### memora-state\n\n- `Db::open` creates or opens `memora.db` (0600 in a 0700 directory), refuses\n foreign or newer-schema files, and runs migrations.\n- Every write is one `BEGIN IMMEDIATE` transaction (`Db::write`), so the server\n and `memora-cli` can write concurrently without losing updates.\n- Sessions are looked up per request by the SHA-256 of the cookie value;\n `last_seen` and key usage are buffered and flushed in the background.\n- The arm window, the LOCKED state, and the last burned window live in one\n `arm_state` row.\n- Triggers bump a per-domain revision counter. The server checks\n `PRAGMA data_version` about once a second and reloads only the caches whose\n domain changed, so CLI edits apply without a restart (except\n `server_config`, which is read at startup).\n- Old rows (activity, key events, sessions, trashed keys, control requests) are\n pruned hourly.\n- See [DATABASE.md](DATABASE.md) for the schema and operations.\n\n### memora-mcp\n\n- `catalog()` returns the full tool list. Each tool carries a name, a category,\n a description, a \"when to use\" note, and a JSON input schema. See\n [MCP.md](MCP.md).\n- `handle()` dispatches JSON-RPC methods: `initialize`,\n `notifications/initialized`, `tools/list`, `tools/call`, `resources/list`,\n and `resources/read`. Unknown methods return JSON-RPC error `-32601`.\n- `call_tool()` dispatches to `MemoryStore` under the caller's privacy view.\n- Every tool call publishes `ai_activity` start and end events.\n- `discovery_card()` builds the `/.well-known/mcp.json` document.\n- `detect_client()` classifies a request as MCP, web, or API from the path, the\n `mcp-session-id` header, the JSON-RPC body shape, and the user agent.\n\n### memora-http\n\n- `build_router()` wires every route and stacks the middleware layers listed\n below.\n- `AppState` holds the shared store, the MCP server, the database handle, the\n in-memory caches (owner, keys, tools, access stack, settings, arm window),\n the rate-limit guard, the allowed domains, the asset directory, and the vault\n path.\n- `oauth.rs` is an OAuth 2.1 authorization server for remote MCP clients;\n `privacy.rs` serves `/api/privacy`; `secrets.rs` seals API key copies.\n\n### memora-cli\n\nThe CLI never asks for the owner password. It opens setup and reset windows and\nprints one-time codes; credentials are always typed into the browser form.\n\n## Request path\n\nA request enters through `axum::serve` on the single bound address. Layers run\nin this order, outermost first:\n\n1. Security headers (`mw_security_headers`): CSP, `X-Frame-Options: DENY`,\n `X-Content-Type-Options`, `Referrer-Policy`, COOP/CORP,\n `Permissions-Policy`, `Cache-Control: no-store` for API and auth responses,\n and HSTS when HTTPS is reported by a trusted proxy. Applied to every\n response, including errors produced by inner layers.\n2. `X-Robots-Tag: noindex` (`mw_noindex`).\n3. A global concurrency limit of 1024 requests.\n4. A 30 second request timeout (`408`).\n5. Guard (`mw_guard`): requests for a host outside the domain allow list get a\n bare `404`. Forwarding headers from untrusted peers are dropped. The caller\n IP is resolved (from `CF-Connecting-IP`, `X-Real-IP`, or the right-most\n `X-Forwarded-For` entry, only when the peer is a trusted proxy). Per-IP\n token buckets apply to auth endpoints and to all traffic, and callers in a\n cooldown after failed logins or bad API keys get `429`. `/healthz` and\n loopback callers are not rate limited.\n6. Access stack (`mw_access`): picks up changes from `memora-cli`, then\n evaluates the caller IP and the `Host` domain against the access rules. A\n block returns `403`. `/healthz` bypasses it.\n7. Auth and lock gate (`mw_auth`):\n - If the instance is LOCKED and the path is neither in the lock allow list\n nor a static asset: `/api/*` and `/mcp` return `423`; other paths redirect\n to `/login?locked=1`.\n - Public paths pass: `/healthz`, `/.well-known/mcp.json`, `/tools`,\n `/login`, `/logout`, `/_bus`, `/`, `/index.html`, static assets, the OAuth\n discovery and flow endpoints, and the auth endpoints\n `/api/auth/{state,login,logout,bootstrap,reset,verify}`.\n - `/ws` needs a valid session and a same-origin request.\n - A valid session cookie (`memora_sess`) passes and is touched (sliding\n TTL).\n - Remaining `/api/*` and `/mcp` requests need an API key, read from\n `Authorization: Bearer <key>` or `X-API-Key: <key>`. The key must carry\n the scope the route needs (`mcp` for `/mcp`, `admin` for keys, tools,\n access, OAuth clients, privacy, and log settings, otherwise `read` for\n GET and `write` for changes). Usage is recorded; an unknown key is logged\n (`key_fail`) and counts toward the IP's cooldown. `/mcp` answers `401`\n with a `WWW-Authenticate` header so OAuth clients can start sign-in.\n8. Vault gate (`mw_vault`): until a vault folder is configured, every route\n that needs the vault (notes, graph, logs, `/mcp`) answers\n `409 {\"needs_vault\": true}`.\n\nThen the matched handler runs. Unmatched browser navigations get the app shell;\nother unmatched paths get a JSON `404`.\n\nFor a browser: `GET /` without a session redirects to `/login`. After login,\nthe UI calls the `/api/*` endpoints. Reads go to `MemoryStore`. Writes from a\ncookie session pass a same-origin check, then call `MemoryStore` `*_impl`\nmethods, which write the note, update the index, and commit to git.\n\nFor an agent: `POST /mcp` carries a JSON-RPC body. The handler parses it,\ndetects the client kind, and calls the MCP server under the key's privacy view.\nA tool call dispatches to the same `MemoryStore` methods the UI uses. REST\ncalls with an API key run under the same privacy view. See [API.md](API.md)\nand [MCP.md](MCP.md).\n\n## Realtime WebSocket fan-out\n\nThe event hub lives in `memora-core::events` as a process-wide singleton.\n\n- `publish()` stamps `_ts`. Persistable event types (`ai_activity` start\n events, `node_created`, `node_updated`, `node_deleted`, `node_renamed`,\n `folder_meta`, `folder_changed`, `actor_alias`, `key_color`) go into a\n 40-entry replay ring and are appended to `<vault>/.events.jsonl`, which is\n trimmed by the `log_max_mb` and `log_max_days` settings.\n- Events are broadcast on a Tokio broadcast channel (capacity 256); a lagging\n subscriber skips missed events instead of stalling the server.\n- `GET /ws` (signed-in browser, same origin, at most 512 clients) sends a\n `hello` event with the client count, replays the ring (each event marked\n `replay: true`), then streams live events. When a client disconnects, a\n `presence` event announces the new count.\n- `POST /_bus` is the local intake: it publishes a JSON object, but only from a\n loopback peer with no forwarding headers. Everyone else gets `403`.\n\nThe WebSocket and the intake bus share the single port. There is no second port\nto open or proxy.\n\n## Auth model\n\nOwner login (browser): the owner posts a username and password to\n`/api/auth/login`. The argon2id hash is verified, a session is created, and the\n`memora_sess` cookie is set (`HttpOnly`, `SameSite=Lax`, `Secure` when HTTPS is\nreported by a trusted proxy). The session slides on activity up to\n`session_ttl`, with an optional absolute cap (`session_max_age`).\n\nAPI keys (agents and scripts): created from the dashboard, the API, or\n`memora-cli` (`/keys`); the raw key is shown once. Only the SHA-256 hex is\nstored, plus an optional encrypted copy (see [Storage model](#storage-model))\nso the owner can show a dashboard-created key again after re-entering the\npassword. Keys carry scopes and an optional tool list.\n\nOAuth 2.1 (remote MCP clients): discovery at\n`/.well-known/oauth-protected-resource` and\n`/.well-known/oauth-authorization-server`; clients register dynamically\n(`/oauth/register`), by a client metadata document URL, or manually by the\nowner. The flow is authorization code with PKCE S256 only. The signed-in owner\napproves the request in the browser, and `/oauth/token` issues an access token\nthat is an ordinary API key, plus a rotating refresh token. Revoking the key\nends the connection.\n\nPrivacy rules: the owner can hide a folder or a note from chosen agents\n(`deny`) or from every agent except chosen ones (`allow_only`). Rules add up;\nthe signed-in owner always sees everything. Rules are managed through\n`/api/privacy` and the admin MCP tools.\n\nFirst-run and recovery (the arm window):\n\n- `GET /api/auth/state` is public and reports `bootstrap` (true when no owner\n exists), `armed`, `locked`, the setup hint, and readiness checks.\n- `memora-cli setup` (or `/web` in the console) arms a `bootstrap` window in\n the `arm_state` row, clearing any lock, and prints a one-time code. The\n browser submits the code and creates the owner through\n `/api/auth/bootstrap`, which works only while armed and only when no owner\n exists.\n- `memora-cli reset-password` arms a `reset` window; `/api/auth/reset`\n replaces the password.\n- A wrong code voids the window. If a window expires unfinished, the instance\n becomes LOCKED. While locked, only the lock allow list and static assets are\n reachable. `memora-cli unlock`, `setup`, or `reset-password` clears the lock.\n\nLock allow list (`LOCK_ALLOWED`): `/login`, `/logout`, `/api/auth/state`,\n`/api/auth/verify`, `/api/auth/login`, `/api/auth/logout`,\n`/api/auth/bootstrap`, `/api/auth/reset`, `/healthz`, `/favicon.ico`.\n\n## Storage model\n\nMemora keeps two directories apart on purpose.\n\n### Vault (markdown, portable)\n\nChosen in the browser after the first sign-in (`MEMORA_VAULT` is the\nsuggestion) and stored in the `settings` table.\n\n- One `.md` file per note. Frontmatter and inline `#tags` are both supported.\n- Wikilinks use `[[Note Name]]` and resolve by name, so moving or renaming a\n note does not break links.\n- `.git/` is the vault history. Changes commit automatically.\n- `.fts.db` is the SQLite search index. It is derived data and can be rebuilt.\n- `.events.jsonl` is the append-only event log.\n- `.folders.json` stores folder color, icon, and description.\n- `.locks.json` stores soft locks used for collaboration.\n- `.actors.json` stores actor aliases.\n- `.Trash/` holds soft-deleted notes, recoverable with `restore_trash`.\n\n### State (credentials, operational)\n\nSet by `MEMORA_STATE` (default `state`).\n\n- `memora.db` is the single SQLite database for all server state: the owner\n (argon2id hash), API keys (SHA-256 hex, with a trash for restore), scopes\n and tool lists, global tool switches, OAuth clients and grants, privacy\n rules, sessions (hashed ids), the arm window and lock, access rules, instance\n settings, `server_config`, UI layouts, and the activity log. It is created\n and migrated on first start; WAL mode, mode 0600.\n- `key-seal.bin` is the 32-byte master key (0600) for the sealed API key copies\n (ChaCha20-Poly1305). The database holds only ciphertext, so a copy of\n `memora.db` alone reveals no key.\n- `backups/` holds `memora-cli db backup` copies.\n- `legacy-json-<unix time>/` holds JSON state files found at startup, moved\n there after their one-time import.\n- `internal.token` is created by the container entrypoint. Memora does not use\n it.\n\nState changes are transactional: a crash leaves either the old or the new\nstate, never a mix.\n",FN="# State database\n\nMemora keeps all server state in one embedded SQLite file,\n`<MEMORA_STATE>/memora.db`, managed by the `memora-state` crate. The vault\n(markdown notes plus git) is separate and stays plain files.\n\nNo SQL lives outside `crates/state`. The server (`memora`) and the operator\nconsole (`memora-cli`) both open the file directly; there is no database\nserver, port, or password.\n\n## Files and permissions\n\n| Path | Mode | Content |\n|---|---|---|\n| `<state>/` | 0700 | The state directory. Created if missing; its mode is tightened on open. |\n| `memora.db` | 0600 | The database. |\n| `memora.db-wal`, `memora.db-shm` | 0600 | WAL journal and shared memory. Part of the live database; never copy `memora.db` without them while the server runs. |\n| `key-seal.bin` | 0600 | Master key for the sealed API key copies (`api_key_secret`). Not inside the database. |\n| `backups/` | 0700 | Output of `memora-cli db backup` and the pre-restore snapshot. |\n| `legacy-json-<unix time>/` | 0700 | JSON state files found at startup, moved here after their one-time import. |\n\nThe state directory must be on a local filesystem. WAL needs shared memory\nand does not work on NFS or SMB; the server refuses to start when WAL cannot be\nenabled.\n\nRun as root, `memora-cli` does every database operation as the owner of the\nstate directory (in a child process that drops privileges), so no root-owned\n`memora.db*` files appear and the server can always open them.\n\n## Connection settings\n\nEvery connection, server and CLI, uses: `journal_mode=WAL`,\n`synchronous=FULL`, `foreign_keys=ON`, `busy_timeout`, `secure_delete=ON`\n(deleted rows are zeroed), `trusted_schema=OFF`, SQLite defensive mode, and a\n4 MiB `journal_size_limit`.\n\nThe file is marked with `PRAGMA application_id = 0x4D454D4F` (`MEMO`). Memora\nrefuses to open a file with another application id, or one whose\n`user_version` is newer than the binary supports.\n\n## Schema\n\nConventions: times are `INTEGER` unix seconds UTC; booleans are\n`INTEGER CHECK (x IN (0,1))`; every table is `STRICT`. Constraints (CHECK,\nUNIQUE, foreign keys, triggers) reject invalid data at the database level; the\nRust repositories validate first to return readable errors. The DDL is in\n`crates/state/migrations/*.sql`.\n\n### Auth and settings\n\n| Table | Content |\n|---|---|\n| `meta` | Key/value markers (for example the legacy import marker). |\n| `owner` | The single owner account: `id` is always 1, so a second account is impossible. Lowercase username (1-32 chars of `a-z0-9._-`), argon2id password hash, display name, timestamps. |\n| `settings` | One row (`id = 1`): `realm`, `session_ttl`, `session_max_age`, `min_password_len`, `log_max_mb`, `log_max_days`, `vault_path` (absolute or NULL). Ranges are listed in [CONFIGURATION.md](CONFIGURATION.md#instance-settings-web-ui). |\n| `server_config` | Server settings that override the environment. Only the ten known keys are accepted, with range checks for `MEMORA_PORT`, `MEMORA_ARM_TTL`, and `MEMORA_VAULT_AUTO`. `MEMORA_ADMIN_PASSWORD` and `MEMORA_API_KEY` cannot be stored. |\n| `arm_state` | One row: `idle`, `armed`, or `locked`, the window mode (`bootstrap` or `reset`), start time, length (30-86400 s), the SHA-256 of the one-time code, lock time, and the last burned window. Checks make an armed row without a code, or a code outside an armed window, impossible. |\n| `session` | Browser sessions keyed by `sid_hash`, the SHA-256 of the cookie value (the cookie itself is never stored). Source, alias, IP, user agent, `created_at`, `last_seen`. The CLI addresses sessions by a prefix of at least 8 characters of `sid_hash`. |\n\n### API keys and tools\n\n| Table | Content |\n|---|---|\n| `api_key` | `id` (`k_...`), name, SHA-256 hex `hash` (unique), display `prefix`, `enabled`, `tools_all`, `color` (`#rrggbb` or NULL), `created_at`, `deleted_at` (trash). `grace_until` is unused and always NULL. |\n| `api_key_scope` | Scopes per key: `mcp`, `read`, `write`, `admin`. |\n| `api_key_tool` | Allowed tools per key, only when `tools_all = 0` (a trigger enforces this and clears the list when `tools_all` is set back to 1). |\n| `api_key_secret` | Optional sealed copy of a dashboard-created key: `base64url(nonce || ChaCha20-Poly1305 ciphertext)` under `key-seal.bin`. |\n| `api_key_usage` | Last use, last IP, and use count per key. Separate from `api_key` so usage flushes do not trigger a key reload. |\n| `api_key_event` | Per-request key events (time, IP, tool or route, path). Used for activity views and new-IP detection. |\n| `tool` | Mirror of the MCP tool catalog, synced at server start. Tools missing from the catalog are marked `retired`. |\n| `tool_disabled` | Globally disabled tools (foreign key to `tool`). |\n\n### OAuth\n\n| Table | Content |\n|---|---|\n| `oauth_client` | Registered clients: `client_id`, name, redirect URIs (JSON array), kind (`dcr`, `cimd`, or `manual`). |\n| `oauth_code` | One-time authorization codes (SHA-256), PKCE S256 challenge, redirect URI, resource, expiry. |\n| `oauth_grant` | Refresh tokens (SHA-256), one per connection, rotated on every use. Each grant points at the API key that serves as its access token and is deleted with it. |\n\n### Access, privacy, and logs\n\n| Table | Content |\n|---|---|\n| `access_policy` | One row: the default action when no rule matches. |\n| `access_rule` | Ordered rules (`position`): kind (`ip`, `range`, `cidr`, `domain`, `all`), value, `allow` or `block`, enabled flag, note. |\n| `privacy_rule` | Hides a vault path from agents: kind `folder` (the folder and everything below it) or `node` (one note), mode `deny` (hidden from the listed keys) or `allow_only` (hidden from every key not listed). Paths are vault-relative and matched case-insensitively. |\n| `privacy_rule_key` | Keys a privacy rule lists. |\n| `privacy_trail` | Earlier paths of a rule after renames and moves (at most 64 per rule), used only to keep log and event lines that name the item away from hidden agents. |\n| `activity` | Audit log: time, event name, IP, actor (username, key id, or `cli`), detail. |\n| `control_request` | Requests from `memora-cli` to the running server for state that lives in server memory (`limiter_reset`, `reload_all`), with an acknowledgement (`done_at`, `result`). |\n| `ui_layout` | One JSON document per web UI layout name (canvas positions, pinned graph positions), at most 512 KiB each. |\n| `pin` | The owner's pinned notes and folders in sidebar order (`position`): kind `note` or `folder`, vault-relative path. At most 200. Renames, moves and deletes done by Memora rewrite or drop them in the same transaction. |\n| `revision` | One counter per cache domain (`auth`, `keys`, `tools`, `access`, `settings`, `arm`), bumped by triggers. |\n\nRevision triggers (one per insert, update, and delete) map tables to domains:\n`owner` to `auth`; `api_key`, `api_key_scope`, `api_key_tool` to `keys`;\n`tool_disabled` to `tools`; `access_policy`, `access_rule` to `access`;\n`settings`, `server_config` to `settings`; `arm_state` to `arm`. Sessions,\nusage, events, activity, OAuth, privacy rules, pins, and UI layouts have no revision\nand are read from the database when needed.\n\n## Concurrency and change detection\n\n- Every write is one transaction started with `BEGIN IMMEDIATE`, so the server\n and `memora-cli` can write at the same time without losing updates.\n `busy_timeout` makes a concurrent writer wait instead of failing.\n Multi-step changes are atomic, for example a password change also deletes the\n other sessions and writes the activity row in the same transaction.\n- The server keeps caches of the owner, keys, tools, access stack, settings,\n and arm window. It checks `PRAGMA data_version` on requests and at least once\n a second; when another connection committed, it reads `revision` and reloads\n only the changed domains. Changes made with `memora-cli` therefore apply on\n the next request, without a restart. `server_config` is the exception: it is\n read at startup.\n- Sessions are not cached: each request looks up `session.sid_hash`, so a\n sign-out from the CLI applies on the next request.\n- Hot-path writes are buffered: session `last_seen` is flushed every 5 seconds\n and key usage every 30 seconds. Pending control requests are served every 2\n seconds. Buffers are flushed on shutdown.\n- Window expiry is a conditional update (`armed` to `locked`), and a setup code\n is checked and consumed in the same transaction, so a code works at most\n once.\n\nKept in memory on purpose: rate-limit token buckets and login cooldowns (a\nrestart resets them; cooldown starts are still written to `activity`), the\ntrusted proxy list, and the caches above.\n\n## Retention\n\nThe server prunes in small batches every hour, and `memora-cli db vacuum` runs\nthe same pruning:\n\n| Data | Kept |\n|---|---|\n| `activity` | 365 days, at most 200,000 rows |\n| `api_key_event` | 30 days, at most 100,000 rows |\n| `session` | Until idle longer than `session_ttl` or older than `session_max_age` |\n| Trashed `api_key` rows | 90 days after `deleted_at` (scopes, tools, usage, and events cascade) |\n| `control_request` | 1 day after `done_at`; unanswered requests expire after 1 hour |\n\n## Migrations\n\nMigrations are SQL files embedded in the binary\n(`crates/state/migrations/0001_init.sql` and onward) and tracked with\n`PRAGMA user_version`. Each one runs in its own `BEGIN IMMEDIATE` transaction\ntogether with the version bump, so a crash leaves either the old or the new\nschema, and two processes opening a fresh file apply it exactly once. The\nserver and `memora-cli` migrate the database when they open it. A binary\nrefuses a database with a newer schema; to go back to an older release,\nrestore the backup taken before upgrading.\n\n| Version | File | Adds |\n|---|---|---|\n| 1 | `0001_init.sql` | Base schema and revision triggers |\n| 2 | `0002_ui_layout.sql` | `ui_layout` |\n| 3 | `0003_colors_logs.sql` | `api_key.color`, `settings.log_max_mb`, `settings.log_max_days` |\n| 4 | `0004_oauth.sql` | `oauth_client`, `oauth_code`, `oauth_grant` |\n| 5 | `0005_key_secret.sql` | `api_key_secret` |\n| 6 | `0006_privacy.sql` | `privacy_rule`, `privacy_rule_key`, `privacy_trail` |\n| 7 | `0007_pins.sql` | `pin` |\n\n### JSON state import\n\nWhen the server starts on a state directory that holds JSON state files\n(`gateway.json`, `config.json`, `memora.env`, `tools.json`,\n`access_stack.json`, `sessions.json`, `arm.json`, `lock.json`,\n`key-usage.json`, `activity.jsonl`, and related files), it imports them once,\nin one transaction, then moves them to `legacy-json-<unix time>/`. Auth data\nmust be valid or nothing is imported; bad log lines are skipped and counted.\nPlaintext `MEMORA_ADMIN_PASSWORD` and `MEMORA_API_KEY` values are dropped. A\nsummary is written to the log and the `activity` table. On a fresh state\ndirectory the import is a no-op.\n\n## Operations\n\n| Task | Command | Notes |\n|---|---|---|\n| Backup (server running) | `memora-cli db backup [--to PATH] [--keep N]` | `VACUUM INTO` a consistent copy, checked with `integrity_check`, mode 0600. Default target `state/backups/memora-<UTC time>.db`; the newest 10 there are kept (`--keep N`). `--to` takes a file or a directory. |\n| Backup without memora-cli | `sqlite3 memora.db \".backup '/var/backups/memora.db'\"` | Never `cp` a live WAL database: recent commits sit in `memora.db-wal`. |\n| Restore | `memora-cli db restore FILE [--force]` | The server must be stopped (the CLI checks for it and for any process holding `memora.db*`; `--force` skips the check). Verifies `application_id`, schema version, `integrity_check`, and foreign keys, saves the current database to `state/backups/memora-<time>-pre-restore.db`, then replaces it and removes stale `-wal`/`-shm` files. |\n| Health | `memora-cli db check` | Directory and file permissions, application id, schema version, `integrity_check`, `foreign_key_check`, file sizes, last backup age. Exit status 1 on any problem, for timers and health checks. |\n| Maintenance | `memora-cli db vacuum` | Prune by retention, `PRAGMA optimize`, `VACUUM`, `wal_checkpoint(TRUNCATE)`. |\n| Inspect | `memora-cli db shell [--write]` | Runs `sqlite3` (must be installed), read-only unless `--write`. Writes through the shell bypass Memora's checks and the activity log. |\n| Export | `memora-cli db export-json [DIR]` | Writes the database out as JSON state files (default: the state directory). |\n\nIn the console: `/backup`, and `/db` with `check`, `vacuum`, or `backup`.\n\nIn Docker, run the same commands through the container:\n\n```sh\ndocker compose exec gateway memora-cli db backup # lands in ./state/backups/\ndocker compose exec gateway memora-cli db check\n```\n\nFor a restore, stop the service first and run the CLI in a one-off container:\n\n```sh\ndocker compose stop gateway\ndocker compose run --rm gateway cli db restore /state/backups/memora-<time>.db\ndocker compose start gateway\n```\n\nA daily systemd timer or cron job running `memora-cli db backup` is enough for\nmost installs. Back up `key-seal.bin` with the database; without it, sealed key\ncopies cannot be shown again (the keys themselves keep working).\n\n## Encryption at rest\n\nThe database is not encrypted. Every credential in it is a one-way hash\n(argon2id for the owner password, SHA-256 for API keys, OAuth codes and refresh\ntokens, setup codes, and session ids), and sealed key copies are encrypted\nunder a key stored outside the database. What remains (IPs, user agents,\nactivity) is low sensitivity. Use a 0700 state directory, host disk\nencryption, and encrypt backups that leave the host (for example with `age` or\n`gpg`).\n",BN='# Tool switches and per-key permissions\n\nThis page describes how Memora decides which MCP tools an agent may see and\ncall. Two controls combine:\n\n- **Global tool switches** turn a tool off for every API key on the server.\n- **Per-key permissions** (scopes and a tool list) limit what one key may do.\n\nThey are managed in the web UI, with `memora-cli` (`/tools` and `/keys`), over\nthe HTTP API, and with the MCP admin tools. All of them write the same state\ndatabase (`state/memora.db`, see [../DATABASE.md](../DATABASE.md)). Tool\nswitches and per-key tool lists from older installs (`state/tools.json` and the\n`tools` field of keys in `gateway.json`) are imported into the database once.\n\n## Tool catalog\n\nThe switchable catalog is `memora_mcp::catalog()`: every tool with its `name`,\n`category`, `description`, when to use it, and input schema (74 tools; see\n[../MCP.md](../MCP.md#tools)). At startup the server mirrors the catalog into\nthe `tool` table, so switches and per-key grants can refer to tools by name.\nA tool that leaves the catalog is marked retired, not deleted: its switch and\ngrants are kept but have no effect, and they apply again if the tool returns.\n\nThe admin tools (`admin_list_tools`, `admin_set_tool`, `privacy_list`,\n`privacy_set`, `privacy_clear`) are not part of the catalog. They cannot be\nswitched off or granted through a tool list; only the `admin` scope controls\nthem.\n\n## Global tool switches\n\nTable `tool_disabled` holds one row per switched-off tool. No row means the tool\nis on. A switched-off tool is hidden from `tools/list` and refused by\n`tools/call` for every caller, browser sessions included. It is still listed in\nthe discovery card and on the `/tools` page, marked as disabled.\n\nSwitching a tool that is already in the requested position changes nothing.\nA change made by another process (for example `memora-cli` while the server\nruns) reaches the server within about a second, without a restart.\n\n## Scopes\n\nEach key has a set of scopes (table `api_key_scope`):\n\n| Scope | Allows |\n|---|---|\n| `mcp` | Calling `/mcp` at all, and every read-only MCP tool. |\n| `read` | `GET` and `HEAD` on the `/api/*` vault routes. |\n| `write` | Mutating `/api/*` vault routes, and every MCP tool that is not read-only. |\n| `admin` | Managing tools, keys, access rules, log settings, OAuth clients and privacy rules (`/api/tools`, `/api/keys`, `/api/access`, `/api/logs/settings`, `/api/oauth/clients`, `/api/privacy` and everything below them), and the MCP admin tools. |\n\nA key created without explicit scopes gets `mcp`, `read` and `write` and every\ntool. Keys that MCP clients obtain through OAuth start with the same defaults.\n`admin` is never granted by default. An empty scope list on create also means\nthe defaults.\n\n## Per-key tool list\n\nEach key either may use every catalog tool (`"tools": "*"`, stored as\n`api_key.tools_all = 1`, the default) or only the tools listed for it\n(`"tools": ["search_memory", "read_memory"]`, stored as `tools_all = 0` plus one\n`api_key_tool` row per tool). An empty list allows no catalog tools. Tool names\nmust be catalog tools; unknown names are refused with `unknown tool: <name>`.\n\nThe tool list does not replace scopes: a tool that changes the vault still\nneeds `write`, even when the list names it.\n\n## Effective access\n\nA key may call catalog tool T over MCP when all of these hold:\n\n1. The key is enabled.\n2. The key has the `mcp` scope.\n3. T is not switched off globally.\n4. The key\'s tool list is `"*"` or contains T.\n5. T is read-only, or the key has the `write` scope.\n\nRead-only tools are the ones listed as read-only in `crates/mcp/src/activity.rs`\n(the R tools in [../MCP.md](../MCP.md#tools)). Every other catalog tool needs\n`write`, including tools added later until they are marked read-only.\n\nAn admin tool may be called when the key is enabled and has both `mcp` and\n`admin`. Browser sessions have full access, including the admin tools, but\nglobal switches still apply to them.\n\nDisabled keys are rejected before MCP runs (HTTP `401`, `invalid API key`), and\na key without `mcp` gets HTTP `403` with\n`{"error":"API key lacks the \'mcp\' scope","required_scope":"mcp"}`.\n\n## How refusals look\n\n`tools/list` returns only the tools the caller may use (plus the admin tools for\nadmin keys).\n\n`tools/call` on a tool the caller may not use returns JSON-RPC error `-32003`\nwith one of these messages:\n\n| Message | Cause |\n|---|---|\n| `tool not allowed for this API key: <name>` | The key\'s tool list does not include the tool, or the caller lacks `admin` for an admin tool. |\n| `tool disabled on this server: <name>` | The tool is switched off globally. |\n| `API key lacks the \'write\' scope for tool: <name>` | The tool is not read-only and the key has no `write` scope. |\n\nA name that is neither a catalog tool nor an admin tool is not refused with\n`-32003`; the call returns a tool result with `isError: true` and\n`unknown tool: <name>`.\n\n## HTTP API\n\nThese routes need a signed-in browser session or an API key with the `admin`\nscope. For browser sessions, `POST` requests must be same-origin.\n\n| Route | Body | Response |\n|---|---|---|\n| `GET /api/tools` | | `{tools: [{name, category, description, enabled}]}` |\n| `POST /api/tools` | `{name, enabled}` | `{ok, name, enabled}`. Unknown tool or missing `enabled`: `400`. |\n| `GET /api/keys` | | `{count, keys}`. Each key includes `tools` (`"*"` or a list) and `scopes`. |\n| `POST /api/keys` | `{name, tools?, scopes?, color?}` | `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. |\n| `POST /api/keys/update` | `{id, name?, enabled?, color?, tools?, scopes?}` | `{ok, id, name, enabled, color, tools, scopes, persisted}` |\n\n`tools` is `"*"` or an array of catalog tool names. `scopes` is an array of\n`mcp`, `read`, `write` and `admin`. Fields left out stay unchanged. Unknown tool\nor scope names return `400` (`unknown tool: <name>`, `unknown scope: <name>`).\n\n## MCP admin tools\n\nListed only for keys with the `admin` scope:\n\n- `admin_list_tools`: no arguments. Same shape as `GET /api/tools`.\n- `admin_set_tool`: `{name, enabled}`. Same effect as `POST /api/tools`.\n\nThe privacy admin tools (`privacy_list`, `privacy_set`, `privacy_clear`) are\ndescribed in [../MCP.md](../MCP.md#admin-tools-admin).\n\n## Activity log\n\nEvery change is written to the `activity` table in the same transaction:\n\n| Event | When | Detail |\n|---|---|---|\n| `tool_enabled` | A tool is switched on | The tool name |\n| `tool_disabled` | A tool is switched off | The tool name |\n| `key_permissions` | A key\'s scopes or tool list are set on create or changed on update | `<id> tools=[...] scopes=[...]` |\n\nCreating and updating a key also logs `key_created` and `key_updated`. The actor\nis the signed-in user, or `key:<id>` when an API key made the change.\n',HN=`# Security Policy
9976
+ `,UN="# Architecture\n\nThis document describes how Memora is put together: the crates, what each one\nowns, the request path from a browser or an agent to the vault, the realtime\nWebSocket fan-out, the auth model, and the storage model. Every claim here maps\nto code under `crates/`.\n\n## Crate layout\n\nMemora is a Cargo workspace with six crates. The web UI is a TypeScript app in\n`web/src`, built with Vite into `crates/http/assets`.\n\n| Crate | Binary | Owns |\n|---|---|---|\n| `memora-core` | (library) | The vault: walking notes, parsing wikilinks and frontmatter, the SQLite search index, search, the graph, git versioning, per-caller path visibility, and the `*_impl` methods that every interface calls. Also the realtime event hub. |\n| `memora-gateway` | (library) | Auth primitives: argon2id password hashing, API key generation and hashing, OAuth token and PKCE helpers, setup codes, the access stack evaluator, host and lock allow lists, scopes and per-key tool permissions, and reading the provisioning environment. No state of its own. |\n| `memora-state` | (library) | The state database `memora.db` (SQLite, WAL): opening, migrations, change detection, and one typed repository per table group (owner, settings, `server_config`, keys, tools, usage, sessions, arm window, access rules, activity, control requests, OAuth, privacy rules, UI layouts, retention), plus the one-time import of JSON state files. No SQL lives outside this crate. |\n| `memora-mcp` | (library) | The MCP server: the tool catalog, JSON-RPC 2.0 handling, the discovery card, client detection, `ai_activity` events, and the privacy view applied to agent callers. |\n| `memora-http` | `memora` | The axum server: routing, middleware, the REST API, OAuth 2.1 endpoints, the privacy API, the WebSocket and intake bus, sealed key copies, and serving the UI assets. |\n| `memora-cli` | `memora-cli` | The operator console (slash commands such as `/guide`, `/web`, `/keys`, `/tools`, `/sessions`, `/config`, `/backup`, `/db`, `/update`) and one-shot commands (`setup`, `reset-password`, `status`, `disarm`, `unlock`, `list`, `clear-cooldowns`, `vault`, `db ...`, `update`, `version`). It opens `memora.db` directly; run as root, it does database work as the state directory's owner. |\n\nDependencies point one way: `http` depends on `core`, `mcp`, `gateway`, and\n`state`; `mcp` depends on `core`, `gateway`, and `state`; `cli` depends on\n`gateway`, `mcp`, and `state`. `core`, `gateway`, and `state` depend on no\nother Memora crate.\n\n## What each crate owns\n\n### memora-core\n\n`MemoryStore` is the single point through which the vault is read and written.\nBoth the HTTP API and the MCP tools call its `*_impl` methods, so a change made\nthrough the UI and one made through an agent take the same code path.\n\n- `walk()` enumerates `.md` files under the vault root, skipping dot\n directories. Walk order is stable, so tools that depend on first-hit order\n behave deterministically.\n- Parsing: wikilinks, inline tags, frontmatter tags, and frontmatter fields.\n- The search index: a SQLite database at `<vault>/.fts.db`. It is derived data\n and is rebuilt when missing.\n- `search()` blends word matching over name and body with `tag:` and `#tag`\n filters, scored by hits, name hits, phrase, and position.\n- The graph: nodes are notes, links are resolved wikilinks.\n- Versioning: vault changes are committed to git (`create:`, `edit:`,\n `rename:`, `move:`, `delete:`, `folder:`); history, diff, restore, and\n snapshot read from that history.\n- Privacy views: while a caller's `PathView` is set, listings skip hidden\n notes, hidden paths resolve as \"not found\", and folder operations that would\n carry hidden items along are refused. A path hook reports renames, moves, and\n deletes so privacy rules follow the notes they protect.\n- The event hub (see below).\n\n### memora-gateway\n\n- `hash_password` and `verify_password` use argon2id.\n- `generate_key` produces `memora_live_` plus 128 random bits as hex.\n `hash_api_key` stores the SHA-256 hex of the key. `verify_key` compares in\n constant time.\n- `AccessStack` evaluates ordered IP, range, CIDR, domain, and catch-all rules.\n Loopback is always allowed.\n- `host_allowed` checks the `Host` against `MEMORA_DOMAIN` and the host of\n `MEMORA_BASE_URL`.\n- `tool_access` combines a key's scopes (`mcp`, `read`, `write`, `admin`), its\n tool list, and the global tool switches.\n\n### memora-state\n\n- `Db::open` creates or opens `memora.db` (0600 in a 0700 directory), refuses\n foreign or newer-schema files, and runs migrations.\n- Every write is one `BEGIN IMMEDIATE` transaction (`Db::write`), so the server\n and `memora-cli` can write concurrently without losing updates.\n- Sessions are looked up per request by the SHA-256 of the cookie value;\n `last_seen` and key usage are buffered and flushed in the background.\n- The arm window, the LOCKED state, and the last burned window live in one\n `arm_state` row.\n- Triggers bump a per-domain revision counter. The server checks\n `PRAGMA data_version` about once a second and reloads only the caches whose\n domain changed, so CLI edits apply without a restart (except\n `server_config`, which is read at startup).\n- Old rows (activity, key events, sessions, trashed keys, control requests) are\n pruned hourly.\n- See [DATABASE.md](DATABASE.md) for the schema and operations.\n\n### memora-mcp\n\n- `catalog()` returns the full tool list. Each tool carries a name, a category,\n a description, a \"when to use\" note, and a JSON input schema. See\n [MCP.md](MCP.md).\n- `handle()` dispatches JSON-RPC methods: `initialize`,\n `notifications/initialized`, `tools/list`, `tools/call`, `resources/list`,\n and `resources/read`. Unknown methods return JSON-RPC error `-32601`.\n- `call_tool()` dispatches to `MemoryStore` under the caller's privacy view.\n- Every tool call publishes `ai_activity` start and end events.\n- `discovery_card()` builds the `/.well-known/mcp.json` document.\n- `detect_client()` classifies a request as MCP, web, or API from the path, the\n `mcp-session-id` header, the JSON-RPC body shape, and the user agent.\n\n### memora-http\n\n- `build_router()` wires every route and stacks the middleware layers listed\n below.\n- `AppState` holds the shared store, the MCP server, the database handle, the\n in-memory caches (owner, keys, tools, access stack, settings, arm window),\n the rate-limit guard, the allowed domains, the asset directory, and the vault\n path.\n- `oauth.rs` is an OAuth 2.1 authorization server for remote MCP clients;\n `privacy.rs` serves `/api/privacy`; `secrets.rs` seals API key copies.\n\n### memora-cli\n\nThe CLI never asks for the owner password. It opens setup and reset windows and\nprints one-time codes; credentials are always typed into the browser form.\n\n## Request path\n\nA request enters through `axum::serve` on the single bound address. Layers run\nin this order, outermost first:\n\n1. Security headers (`mw_security_headers`): CSP, `X-Frame-Options: DENY`,\n `X-Content-Type-Options`, `Referrer-Policy`, COOP/CORP,\n `Permissions-Policy`, `Cache-Control: no-store` for API and auth responses,\n and HSTS when HTTPS is reported by a trusted proxy. Applied to every\n response, including errors produced by inner layers.\n2. `X-Robots-Tag: noindex` (`mw_noindex`).\n3. A global concurrency limit of 1024 requests.\n4. A 30 second request timeout (`408`).\n5. Guard (`mw_guard`): requests for a host outside the domain allow list get a\n bare `404`. Forwarding headers from untrusted peers are dropped. The caller\n IP is resolved (from `CF-Connecting-IP`, `X-Real-IP`, or the right-most\n `X-Forwarded-For` entry, only when the peer is a trusted proxy). Per-IP\n token buckets apply to auth endpoints and to all traffic, and callers in a\n cooldown after failed logins or bad API keys get `429`. `/healthz` and\n loopback callers are not rate limited.\n6. Access stack (`mw_access`): picks up changes from `memora-cli`, then\n evaluates the caller IP and the `Host` domain against the access rules. A\n block returns `403`. `/healthz` bypasses it.\n7. Auth and lock gate (`mw_auth`):\n - If the instance is LOCKED and the path is neither in the lock allow list\n nor a static asset: `/api/*` and `/mcp` return `423`; other paths redirect\n to `/login?locked=1`.\n - Public paths pass: `/healthz`, `/.well-known/mcp.json`, `/tools`,\n `/login`, `/logout`, `/_bus`, `/`, `/index.html`, static assets, the OAuth\n discovery and flow endpoints, and the auth endpoints\n `/api/auth/{state,login,logout,bootstrap,reset,verify}`.\n - `/ws` needs a valid session and a same-origin request.\n - A valid session cookie (`memora_sess`) passes and is touched (sliding\n TTL).\n - Remaining `/api/*` and `/mcp` requests need an API key, read from\n `Authorization: Bearer <key>` or `X-API-Key: <key>`. The key must carry\n the scope the route needs (`mcp` for `/mcp`, `admin` for keys, tools,\n access, OAuth clients, privacy, and log settings, otherwise `read` for\n GET and `write` for changes). Usage is recorded; an unknown key is logged\n (`key_fail`) and counts toward the IP's cooldown. `/mcp` answers `401`\n with a `WWW-Authenticate` header so OAuth clients can start sign-in.\n8. Vault gate (`mw_vault`): until a vault folder is configured, every route\n that needs the vault (notes, graph, logs, `/mcp`) answers\n `409 {\"needs_vault\": true}`.\n\nThen the matched handler runs. Unmatched browser navigations get the app shell;\nother unmatched paths get a JSON `404`.\n\nFor a browser: `GET /` without a session redirects to `/login`. After login,\nthe UI calls the `/api/*` endpoints. Reads go to `MemoryStore`. Writes from a\ncookie session pass a same-origin check, then call `MemoryStore` `*_impl`\nmethods, which write the note, update the index, and commit to git.\n\nFor an agent: `POST /mcp` carries a JSON-RPC body. The handler parses it,\ndetects the client kind, and calls the MCP server under the key's privacy view.\nA tool call dispatches to the same `MemoryStore` methods the UI uses. REST\ncalls with an API key run under the same privacy view. See [API.md](API.md)\nand [MCP.md](MCP.md).\n\n## Realtime WebSocket fan-out\n\nThe event hub lives in `memora-core::events` as a process-wide singleton.\n\n- `publish()` stamps `_ts`. Persistable event types (`ai_activity` start\n events, `node_created`, `node_updated`, `node_deleted`, `node_renamed`,\n `folder_meta`, `folder_changed`, `actor_alias`, `key_color`) go into a\n 40-entry replay ring and are appended to `<vault>/.events.jsonl`, which is\n trimmed by the `log_max_mb` and `log_max_days` settings.\n- Events are broadcast on a Tokio broadcast channel (capacity 256); a lagging\n subscriber skips missed events instead of stalling the server.\n- `GET /ws` (signed-in browser, same origin, at most 512 clients) sends a\n `hello` event with the client count, replays the ring (each event marked\n `replay: true`), then streams live events. When a client disconnects, a\n `presence` event announces the new count.\n- `POST /_bus` is the local intake: it publishes a JSON object, but only from a\n loopback peer with no forwarding headers. Everyone else gets `403`.\n\nThe WebSocket and the intake bus share the single port. There is no second port\nto open or proxy.\n\n## Auth model\n\nOwner login (browser): the owner posts a username and password to\n`/api/auth/login`. The argon2id hash is verified, a session is created, and the\n`memora_sess` cookie is set (`HttpOnly`, `SameSite=Lax`, `Secure` when HTTPS is\nreported by a trusted proxy). The session slides on activity up to\n`session_ttl`, with an optional absolute cap (`session_max_age`).\n\nAPI keys (agents and scripts): created from the dashboard, the API, or\n`memora-cli` (`/keys`); the raw key is shown once. Only the SHA-256 hex is\nstored, plus an optional encrypted copy (see [Storage model](#storage-model))\nso the owner can show a dashboard-created key again after re-entering the\npassword. Keys carry scopes and an optional tool list.\n\nOAuth 2.1 (remote MCP clients): discovery at\n`/.well-known/oauth-protected-resource` and\n`/.well-known/oauth-authorization-server`; clients register dynamically\n(`/oauth/register`), by a client metadata document URL, or manually by the\nowner. The flow is authorization code with PKCE S256 only. The signed-in owner\napproves the request in the browser, and `/oauth/token` issues an access token\nthat is an ordinary API key, plus a rotating refresh token. Revoking the key\nends the connection.\n\nPrivacy rules: the owner can hide a folder or a note from chosen agents\n(`deny`) or from every agent except chosen ones (`allow_only`). Rules add up;\nthe signed-in owner always sees everything. Rules are managed through\n`/api/privacy` and the admin MCP tools.\n\nFirst-run and recovery (the arm window):\n\n- `GET /api/auth/state` is public and reports `bootstrap` (true when no owner\n exists), `armed`, `locked`, the setup hint, and readiness checks.\n- `memora-cli setup` (or `/web` in the console) arms a `bootstrap` window in\n the `arm_state` row, clearing any lock, and prints a one-time code. The\n browser submits the code and creates the owner through\n `/api/auth/bootstrap`, which works only while armed and only when no owner\n exists.\n- `memora-cli reset-password` arms a `reset` window; `/api/auth/reset`\n replaces the password.\n- A wrong code voids the window. If a window expires unfinished, the instance\n becomes LOCKED. While locked, only the lock allow list and static assets are\n reachable. `memora-cli unlock`, `setup`, or `reset-password` clears the lock.\n\nLock allow list (`LOCK_ALLOWED`): `/login`, `/logout`, `/api/auth/state`,\n`/api/auth/verify`, `/api/auth/login`, `/api/auth/logout`,\n`/api/auth/bootstrap`, `/api/auth/reset`, `/healthz`, `/favicon.ico`.\n\n## Storage model\n\nMemora keeps two directories apart on purpose.\n\n### Vault (markdown, portable)\n\nChosen in the browser after the first sign-in (`MEMORA_VAULT` is the\nsuggestion) and stored in the `settings` table.\n\n- One `.md` file per note. Frontmatter and inline `#tags` are both supported.\n- Wikilinks use `[[Note Name]]` and resolve by name, so moving or renaming a\n note does not break links.\n- `.git/` is the vault history. Changes commit automatically.\n- `.fts.db` is the SQLite search index. It is derived data and can be rebuilt.\n- `.events.jsonl` is the append-only event log.\n- `.folders.json` stores folder color, icon, and description.\n- `.locks.json` stores soft locks used for collaboration.\n- `.actors.json` stores actor aliases.\n- `.Trash/` holds soft-deleted notes, recoverable with `restore_trash`.\n\n### State (credentials, operational)\n\nSet by `MEMORA_STATE` (default `state`).\n\n- `memora.db` is the single SQLite database for all server state: the owner\n (argon2id hash), API keys (SHA-256 hex, with a trash for restore), scopes\n and tool lists, global tool switches, OAuth clients and grants, privacy\n rules, sessions (hashed ids), the arm window and lock, access rules, instance\n settings, `server_config`, UI layouts, and the activity log. It is created\n and migrated on first start; WAL mode, mode 0600.\n- `key-seal.bin` is the 32-byte master key (0600) for the sealed API key copies\n (ChaCha20-Poly1305). The database holds only ciphertext, so a copy of\n `memora.db` alone reveals no key.\n- `backups/` holds `memora-cli db backup` copies.\n- `legacy-json-<unix time>/` holds JSON state files found at startup, moved\n there after their one-time import.\n- `internal.token` is created by the container entrypoint. Memora does not use\n it.\n\nState changes are transactional: a crash leaves either the old or the new\nstate, never a mix.\n",FN="# State database\n\nMemora keeps all server state in one embedded SQLite file,\n`<MEMORA_STATE>/memora.db`, managed by the `memora-state` crate. The vault\n(markdown notes plus git) is separate and stays plain files.\n\nNo SQL lives outside `crates/state`. The server (`memora`) and the operator\nconsole (`memora-cli`) both open the file directly; there is no database\nserver, port, or password.\n\n## Files and permissions\n\n| Path | Mode | Content |\n|---|---|---|\n| `<state>/` | 0700 | The state directory. Created if missing; its mode is tightened on open. |\n| `memora.db` | 0600 | The database. |\n| `memora.db-wal`, `memora.db-shm` | 0600 | WAL journal and shared memory. Part of the live database; never copy `memora.db` without them while the server runs. |\n| `key-seal.bin` | 0600 | Master key for the sealed API key copies (`api_key_secret`). Not inside the database. |\n| `backups/` | 0700 | Output of `memora-cli db backup` and the pre-restore snapshot. |\n| `legacy-json-<unix time>/` | 0700 | JSON state files found at startup, moved here after their one-time import. |\n\nThe state directory must be on a local filesystem. WAL needs shared memory\nand does not work on NFS or SMB; the server refuses to start when WAL cannot be\nenabled.\n\nRun as root, `memora-cli` does every database operation as the owner of the\nstate directory (in a child process that drops privileges), so no root-owned\n`memora.db*` files appear and the server can always open them.\n\n## Connection settings\n\nEvery connection, server and CLI, uses: `journal_mode=WAL`,\n`synchronous=FULL`, `foreign_keys=ON`, `busy_timeout`, `secure_delete=ON`\n(deleted rows are zeroed), `trusted_schema=OFF`, SQLite defensive mode, and a\n4 MiB `journal_size_limit`.\n\nThe file is marked with `PRAGMA application_id = 0x4D454D4F` (`MEMO`). Memora\nrefuses to open a file with another application id, or one whose\n`user_version` is newer than the binary supports.\n\n## Schema\n\nConventions: times are `INTEGER` unix seconds UTC; booleans are\n`INTEGER CHECK (x IN (0,1))`; every table is `STRICT`. Constraints (CHECK,\nUNIQUE, foreign keys, triggers) reject invalid data at the database level; the\nRust repositories validate first to return readable errors. The DDL is in\n`crates/state/migrations/*.sql`.\n\n### Auth and settings\n\n| Table | Content |\n|---|---|\n| `meta` | Key/value markers (for example the legacy import marker). |\n| `owner` | The single owner account: `id` is always 1, so a second account is impossible. Lowercase username (1-32 chars of `a-z0-9._-`), argon2id password hash, display name, timestamps. |\n| `settings` | One row (`id = 1`): `realm`, `session_ttl`, `session_max_age`, `min_password_len`, `log_max_mb`, `log_max_days`, `vault_path` (absolute or NULL). Ranges are listed in [CONFIGURATION.md](CONFIGURATION.md#instance-settings-web-ui). |\n| `server_config` | Server settings that override the environment. Only the ten known keys are accepted, with range checks for `MEMORA_PORT`, `MEMORA_ARM_TTL`, and `MEMORA_VAULT_AUTO`. `MEMORA_ADMIN_PASSWORD` and `MEMORA_API_KEY` cannot be stored. |\n| `arm_state` | One row: `idle`, `armed`, or `locked`, the window mode (`bootstrap` or `reset`), start time, length (30-86400 s), the SHA-256 of the one-time code, lock time, and the last burned window. Checks make an armed row without a code, or a code outside an armed window, impossible. |\n| `session` | Browser sessions keyed by `sid_hash`, the SHA-256 of the cookie value (the cookie itself is never stored). Source, alias, IP, user agent, `created_at`, `last_seen`. The CLI addresses sessions by a prefix of at least 8 characters of `sid_hash`. |\n\n### API keys and tools\n\n| Table | Content |\n|---|---|\n| `api_key` | `id` (`k_...`), name, SHA-256 hex `hash` (unique), display `prefix`, `enabled`, `tools_all`, `color` (`#rrggbb` or NULL), `created_at`, `deleted_at` (trash). `grace_until` is unused and always NULL. |\n| `api_key_scope` | Scopes per key: `mcp`, `read`, `write`, `admin`. |\n| `api_key_tool` | Allowed tools per key, only when `tools_all = 0` (a trigger enforces this and clears the list when `tools_all` is set back to 1). |\n| `api_key_secret` | Optional sealed copy of a dashboard-created key: `base64url(nonce || ChaCha20-Poly1305 ciphertext)` under `key-seal.bin`. |\n| `api_key_usage` | Last use, last IP, and use count per key. Separate from `api_key` so usage flushes do not trigger a key reload. |\n| `api_key_event` | Per-request key events (time, IP, tool or route, path). Used for activity views and new-IP detection. |\n| `tool` | Mirror of the MCP tool catalog, synced at server start. Tools missing from the catalog are marked `retired`. |\n| `tool_disabled` | Globally disabled tools (foreign key to `tool`). |\n\n### OAuth\n\n| Table | Content |\n|---|---|\n| `oauth_client` | Registered clients: `client_id`, name, redirect URIs (JSON array), kind (`dcr`, `cimd`, or `manual`). |\n| `oauth_code` | One-time authorization codes (SHA-256), PKCE S256 challenge, redirect URI, resource, expiry. |\n| `oauth_grant` | Refresh tokens (SHA-256), one per connection, rotated on every use. Each grant points at the API key that serves as its access token and is deleted with it. |\n\n### Access, privacy, and logs\n\n| Table | Content |\n|---|---|\n| `access_policy` | One row: the default action when no rule matches. |\n| `access_rule` | Ordered rules (`position`): kind (`ip`, `range`, `cidr`, `domain`, `all`), value, `allow` or `block`, enabled flag, note. |\n| `privacy_rule` | Hides a vault path from agents: kind `folder` (the folder and everything below it) or `node` (one note), mode `deny` (hidden from the listed keys) or `allow_only` (hidden from every key not listed). Paths are vault-relative and matched case-insensitively. |\n| `privacy_rule_key` | Keys a privacy rule lists. |\n| `privacy_trail` | Earlier paths of a rule after renames and moves (at most 64 per rule), used only to keep log and event lines that name the item away from hidden agents. |\n| `activity` | Audit log: time, event name, IP, actor (username, key id, or `cli`), detail. |\n| `control_request` | Requests from `memora-cli` to the running server for state that lives in server memory (`limiter_reset`, `reload_all`), with an acknowledgement (`done_at`, `result`). |\n| `ui_layout` | One JSON document per web UI layout name (canvas positions, pinned graph positions), at most 512 KiB each. |\n| `pin` | The owner's pinned notes and folders in sidebar order (`position`): kind `note` or `folder`, vault-relative path. At most 200. Renames, moves and deletes done by Memora rewrite or drop them in the same transaction. |\n| `revision` | One counter per cache domain (`auth`, `keys`, `tools`, `access`, `settings`, `arm`), bumped by triggers. |\n\nRevision triggers (one per insert, update, and delete) map tables to domains:\n`owner` to `auth`; `api_key`, `api_key_scope`, `api_key_tool` to `keys`;\n`tool_disabled` to `tools`; `access_policy`, `access_rule` to `access`;\n`settings`, `server_config` to `settings`; `arm_state` to `arm`. Sessions,\nusage, events, activity, OAuth, privacy rules, pins, and UI layouts have no revision\nand are read from the database when needed.\n\n## Concurrency and change detection\n\n- Every write is one transaction started with `BEGIN IMMEDIATE`, so the server\n and `memora-cli` can write at the same time without losing updates.\n `busy_timeout` makes a concurrent writer wait instead of failing.\n Multi-step changes are atomic, for example a password change also deletes the\n other sessions and writes the activity row in the same transaction.\n- The server keeps caches of the owner, keys, tools, access stack, settings,\n and arm window. It checks `PRAGMA data_version` on requests and at least once\n a second; when another connection committed, it reads `revision` and reloads\n only the changed domains. Changes made with `memora-cli` therefore apply on\n the next request, without a restart. `server_config` is the exception: it is\n read at startup.\n- Sessions are not cached: each request looks up `session.sid_hash`, so a\n sign-out from the CLI applies on the next request.\n- Hot-path writes are buffered: session `last_seen` is flushed every 5 seconds\n and key usage every 30 seconds. Pending control requests are served every 2\n seconds. Buffers are flushed on shutdown.\n- Window expiry is a conditional update (`armed` to `locked`), and a setup code\n is checked and consumed in the same transaction, so a code works at most\n once.\n\nKept in memory on purpose: rate-limit token buckets and login cooldowns (a\nrestart resets them; cooldown starts are still written to `activity`), the\ntrusted proxy list, and the caches above.\n\n## Retention\n\nThe server prunes in small batches every hour, and `memora-cli db vacuum` runs\nthe same pruning:\n\n| Data | Kept |\n|---|---|\n| `activity` | 365 days, at most 200,000 rows |\n| `api_key_event` | 30 days, at most 100,000 rows |\n| `session` | Until idle longer than `session_ttl` or older than `session_max_age` |\n| Trashed `api_key` rows | 90 days after `deleted_at` (scopes, tools, usage, and events cascade) |\n| `control_request` | 1 day after `done_at`; unanswered requests expire after 1 hour |\n\n## Migrations\n\nMigrations are SQL files embedded in the binary\n(`crates/state/migrations/0001_init.sql` and onward) and tracked with\n`PRAGMA user_version`. Each one runs in its own `BEGIN IMMEDIATE` transaction\ntogether with the version bump, so a crash leaves either the old or the new\nschema, and two processes opening a fresh file apply it exactly once. The\nserver and `memora-cli` migrate the database when they open it. A binary\nrefuses a database with a newer schema; to go back to an older release,\nrestore the backup taken before upgrading.\n\n| Version | File | Adds |\n|---|---|---|\n| 1 | `0001_init.sql` | Base schema and revision triggers |\n| 2 | `0002_ui_layout.sql` | `ui_layout` |\n| 3 | `0003_colors_logs.sql` | `api_key.color`, `settings.log_max_mb`, `settings.log_max_days` |\n| 4 | `0004_oauth.sql` | `oauth_client`, `oauth_code`, `oauth_grant` |\n| 5 | `0005_key_secret.sql` | `api_key_secret` |\n| 6 | `0006_privacy.sql` | `privacy_rule`, `privacy_rule_key`, `privacy_trail` |\n| 7 | `0007_pins.sql` | `pin` |\n| 8 | `0008_windows_vault_path.sql` | `settings.vault_path` accepts Windows absolute paths (table rebuilt) |\n\n### JSON state import\n\nWhen the server starts on a state directory that holds JSON state files\n(`gateway.json`, `config.json`, `memora.env`, `tools.json`,\n`access_stack.json`, `sessions.json`, `arm.json`, `lock.json`,\n`key-usage.json`, `activity.jsonl`, and related files), it imports them once,\nin one transaction, then moves them to `legacy-json-<unix time>/`. Auth data\nmust be valid or nothing is imported; bad log lines are skipped and counted.\nPlaintext `MEMORA_ADMIN_PASSWORD` and `MEMORA_API_KEY` values are dropped. A\nsummary is written to the log and the `activity` table. On a fresh state\ndirectory the import is a no-op.\n\n## Operations\n\n| Task | Command | Notes |\n|---|---|---|\n| Backup (server running) | `memora-cli db backup [--to PATH] [--keep N]` | `VACUUM INTO` a consistent copy, checked with `integrity_check`, mode 0600. Default target `state/backups/memora-<UTC time>.db`; the newest 10 there are kept (`--keep N`). `--to` takes a file or a directory. |\n| Backup without memora-cli | `sqlite3 memora.db \".backup '/var/backups/memora.db'\"` | Never `cp` a live WAL database: recent commits sit in `memora.db-wal`. |\n| Restore | `memora-cli db restore FILE [--force]` | The server must be stopped (the CLI checks for it and for any process holding `memora.db*`; `--force` skips the check). Verifies `application_id`, schema version, `integrity_check`, and foreign keys, saves the current database to `state/backups/memora-<time>-pre-restore.db`, then replaces it and removes stale `-wal`/`-shm` files. |\n| Health | `memora-cli db check` | Directory and file permissions, application id, schema version, `integrity_check`, `foreign_key_check`, file sizes, last backup age. Exit status 1 on any problem, for timers and health checks. |\n| Maintenance | `memora-cli db vacuum` | Prune by retention, `PRAGMA optimize`, `VACUUM`, `wal_checkpoint(TRUNCATE)`. |\n| Inspect | `memora-cli db shell [--write]` | Runs `sqlite3` (must be installed), read-only unless `--write`. Writes through the shell bypass Memora's checks and the activity log. |\n| Export | `memora-cli db export-json [DIR]` | Writes the database out as JSON state files (default: the state directory). |\n\nIn the console: `/backup`, and `/db` with `check`, `vacuum`, or `backup`.\n\nIn Docker, run the same commands through the container:\n\n```sh\ndocker compose exec gateway memora-cli db backup # lands in ./state/backups/\ndocker compose exec gateway memora-cli db check\n```\n\nFor a restore, stop the service first and run the CLI in a one-off container:\n\n```sh\ndocker compose stop gateway\ndocker compose run --rm gateway cli db restore /state/backups/memora-<time>.db\ndocker compose start gateway\n```\n\nA daily systemd timer or cron job running `memora-cli db backup` is enough for\nmost installs. Back up `key-seal.bin` with the database; without it, sealed key\ncopies cannot be shown again (the keys themselves keep working).\n\n## Encryption at rest\n\nThe database is not encrypted. Every credential in it is a one-way hash\n(argon2id for the owner password, SHA-256 for API keys, OAuth codes and refresh\ntokens, setup codes, and session ids), and sealed key copies are encrypted\nunder a key stored outside the database. What remains (IPs, user agents,\nactivity) is low sensitivity. Use a 0700 state directory, host disk\nencryption, and encrypt backups that leave the host (for example with `age` or\n`gpg`).\n",BN='# Tool switches and per-key permissions\n\nThis page describes how Memora decides which MCP tools an agent may see and\ncall. Two controls combine:\n\n- **Global tool switches** turn a tool off for every API key on the server.\n- **Per-key permissions** (scopes and a tool list) limit what one key may do.\n\nThey are managed in the web UI, with `memora-cli` (`/tools` and `/keys`), over\nthe HTTP API, and with the MCP admin tools. All of them write the same state\ndatabase (`state/memora.db`, see [../DATABASE.md](../DATABASE.md)). Tool\nswitches and per-key tool lists from older installs (`state/tools.json` and the\n`tools` field of keys in `gateway.json`) are imported into the database once.\n\n## Tool catalog\n\nThe switchable catalog is `memora_mcp::catalog()`: every tool with its `name`,\n`category`, `description`, when to use it, and input schema (74 tools; see\n[../MCP.md](../MCP.md#tools)). At startup the server mirrors the catalog into\nthe `tool` table, so switches and per-key grants can refer to tools by name.\nA tool that leaves the catalog is marked retired, not deleted: its switch and\ngrants are kept but have no effect, and they apply again if the tool returns.\n\nThe admin tools (`admin_list_tools`, `admin_set_tool`, `privacy_list`,\n`privacy_set`, `privacy_clear`) are not part of the catalog. They cannot be\nswitched off or granted through a tool list; only the `admin` scope controls\nthem.\n\n## Global tool switches\n\nTable `tool_disabled` holds one row per switched-off tool. No row means the tool\nis on. A switched-off tool is hidden from `tools/list` and refused by\n`tools/call` for every caller, browser sessions included. It is still listed in\nthe discovery card and on the `/tools` page, marked as disabled.\n\nSwitching a tool that is already in the requested position changes nothing.\nA change made by another process (for example `memora-cli` while the server\nruns) reaches the server within about a second, without a restart.\n\n## Scopes\n\nEach key has a set of scopes (table `api_key_scope`):\n\n| Scope | Allows |\n|---|---|\n| `mcp` | Calling `/mcp` at all, and every read-only MCP tool. |\n| `read` | `GET` and `HEAD` on the `/api/*` vault routes. |\n| `write` | Mutating `/api/*` vault routes, and every MCP tool that is not read-only. |\n| `admin` | Managing tools, keys, access rules, log settings, OAuth clients and privacy rules (`/api/tools`, `/api/keys`, `/api/access`, `/api/logs/settings`, `/api/oauth/clients`, `/api/privacy` and everything below them), and the MCP admin tools. |\n\nA key created without explicit scopes gets `mcp`, `read` and `write` and every\ntool. Keys that MCP clients obtain through OAuth start with the same defaults.\n`admin` is never granted by default. An empty scope list on create also means\nthe defaults.\n\n## Per-key tool list\n\nEach key either may use every catalog tool (`"tools": "*"`, stored as\n`api_key.tools_all = 1`, the default) or only the tools listed for it\n(`"tools": ["search_memory", "read_memory"]`, stored as `tools_all = 0` plus one\n`api_key_tool` row per tool). An empty list allows no catalog tools. Tool names\nmust be catalog tools; unknown names are refused with `unknown tool: <name>`.\n\nThe tool list does not replace scopes: a tool that changes the vault still\nneeds `write`, even when the list names it.\n\n## Effective access\n\nA key may call catalog tool T over MCP when all of these hold:\n\n1. The key is enabled.\n2. The key has the `mcp` scope.\n3. T is not switched off globally.\n4. The key\'s tool list is `"*"` or contains T.\n5. T is read-only, or the key has the `write` scope.\n\nRead-only tools are the ones listed as read-only in `crates/mcp/src/activity.rs`\n(the R tools in [../MCP.md](../MCP.md#tools)). Every other catalog tool needs\n`write`, including tools added later until they are marked read-only.\n\nAn admin tool may be called when the key is enabled and has both `mcp` and\n`admin`. Browser sessions have full access, including the admin tools, but\nglobal switches still apply to them.\n\nDisabled keys are rejected before MCP runs (HTTP `401`, `invalid API key`), and\na key without `mcp` gets HTTP `403` with\n`{"error":"API key lacks the \'mcp\' scope","required_scope":"mcp"}`.\n\n## How refusals look\n\n`tools/list` returns only the tools the caller may use (plus the admin tools for\nadmin keys).\n\n`tools/call` on a tool the caller may not use returns JSON-RPC error `-32003`\nwith one of these messages:\n\n| Message | Cause |\n|---|---|\n| `tool not allowed for this API key: <name>` | The key\'s tool list does not include the tool, or the caller lacks `admin` for an admin tool. |\n| `tool disabled on this server: <name>` | The tool is switched off globally. |\n| `API key lacks the \'write\' scope for tool: <name>` | The tool is not read-only and the key has no `write` scope. |\n\nA name that is neither a catalog tool nor an admin tool is not refused with\n`-32003`; the call returns a tool result with `isError: true` and\n`unknown tool: <name>`.\n\n## HTTP API\n\nThese routes need a signed-in browser session or an API key with the `admin`\nscope. For browser sessions, `POST` requests must be same-origin.\n\n| Route | Body | Response |\n|---|---|---|\n| `GET /api/tools` | | `{tools: [{name, category, description, enabled}]}` |\n| `POST /api/tools` | `{name, enabled}` | `{ok, name, enabled}`. Unknown tool or missing `enabled`: `400`. |\n| `GET /api/keys` | | `{count, keys}`. Each key includes `tools` (`"*"` or a list) and `scopes`. |\n| `POST /api/keys` | `{name, tools?, scopes?, color?}` | `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. |\n| `POST /api/keys/update` | `{id, name?, enabled?, color?, tools?, scopes?}` | `{ok, id, name, enabled, color, tools, scopes, persisted}` |\n\n`tools` is `"*"` or an array of catalog tool names. `scopes` is an array of\n`mcp`, `read`, `write` and `admin`. Fields left out stay unchanged. Unknown tool\nor scope names return `400` (`unknown tool: <name>`, `unknown scope: <name>`).\n\n## MCP admin tools\n\nListed only for keys with the `admin` scope:\n\n- `admin_list_tools`: no arguments. Same shape as `GET /api/tools`.\n- `admin_set_tool`: `{name, enabled}`. Same effect as `POST /api/tools`.\n\nThe privacy admin tools (`privacy_list`, `privacy_set`, `privacy_clear`) are\ndescribed in [../MCP.md](../MCP.md#admin-tools-admin).\n\n## Activity log\n\nEvery change is written to the `activity` table in the same transaction:\n\n| Event | When | Detail |\n|---|---|---|\n| `tool_enabled` | A tool is switched on | The tool name |\n| `tool_disabled` | A tool is switched off | The tool name |\n| `key_permissions` | A key\'s scopes or tool list are set on create or changed on update | `<id> tools=[...] scopes=[...]` |\n\nCreating and updating a key also logs `key_created` and `key_updated`. The actor\nis the signed-in user, or `key:<id>` when an API key made the change.\n',HN=`# Security Policy
9929
9977
 
9930
9978
  ## Supported versions
9931
9979
 
@@ -10007,6 +10055,36 @@ All notable changes to this project are documented in this file.
10007
10055
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
10008
10056
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
10009
10057
 
10058
+ ## [1.3.0] - 2026-10-19
10059
+
10060
+ ### Added
10061
+
10062
+ - Native Windows support: \`memora\` and \`memora-cli\` build and run on Windows
10063
+ 10/11 (x64), and \`npm install -g @codrihub/memora\` installs the new
10064
+ \`@codrihub/memora-win32-x64\` package there. The release workflow builds it
10065
+ with a static C runtime.
10066
+ - A Windows zip on every GitHub release
10067
+ (\`memora-<version>-x86_64-windows.zip\`, listed in \`SHA256SUMS\`) with
10068
+ \`memora.exe\`, \`memora-cli.exe\` and the web UI: unzip and run, no installer
10069
+ or Node needed.
10070
+
10071
+ ### Changed
10072
+
10073
+ - On Windows, \`memora-cli\` runs database work in-process (there is no root
10074
+ privilege drop), reports state files as private, and finds \`sqlite3.exe\`
10075
+ on \`PATH\` for \`db shell\`.
10076
+ - The vault folder may be a Windows absolute path (\`C:\\...\` or
10077
+ \`\\\\server\\share\`). Migration 8 rebuilds the \`settings\` table so the
10078
+ database accepts it; Unix paths are unchanged. On Windows, system folders
10079
+ (\`%SystemRoot%\`, \`%ProgramFiles%\`, \`%ProgramData%\`) are refused as vaults.
10080
+ - \`memora\` finds its web UI in an \`assets\` folder next to the executable
10081
+ (an unpacked release zip or tarball) when \`MEMORA_ASSETS\` is not set.
10082
+
10083
+ ### Fixed
10084
+
10085
+ - The Windows system-folder check compares paths without regard to case, so
10086
+ \`C:\\Windows\` is refused even when \`%SystemRoot%\` reads \`C:\\WINDOWS\`.
10087
+
10010
10088
  ## [1.2.3] - 2026-10-19
10011
10089
 
10012
10090
  ### Added
@@ -10217,6 +10295,7 @@ First public release.
10217
10295
  - Docker image, Docker Compose file and an installer script with checksum
10218
10296
  verification.
10219
10297
 
10298
+ [1.3.0]: https://github.com/Codrihub/memora/releases/tag/v1.3.0
10220
10299
  [1.2.3]: https://github.com/Codrihub/memora/releases/tag/v1.2.3
10221
10300
  [1.2.2]: https://github.com/Codrihub/memora/releases/tag/v1.2.2
10222
10301
  [1.2.1]: https://github.com/Codrihub/memora/releases/tag/v1.2.1
@@ -10228,33 +10307,34 @@ First public release.
10228
10307
  [1.1.1]: https://github.com/Codrihub/memora/releases/tag/v1.1.1
10229
10308
  [1.1.0]: https://github.com/Codrihub/memora/releases/tag/v1.1.0
10230
10309
  [1.0.0]: https://github.com/Codrihub/memora/releases/tag/v1.0.0
10231
- `,O_="https://github.com/Codrihub/memora"+"/blob/main/",qN={"README.md":"get-started","docs/INSTALL.md":"install","docs/CONFIGURATION.md":"configuration","docs/MCP.md":"mcp","docs/API.md":"api","docs/DEPLOYMENT.md":"deployment","docs/ARCHITECTURE.md":"architecture","docs/DATABASE.md":"database","docs/contracts/tools-permissions.md":"tool-reference","SECURITY.md":"security","CHANGELOG.md":"changelog"};function VN(n,e){const t=n.split("/").slice(0,-1);for(const i of e.split("/"))if(!(i===""||i==="."))if(i===".."){if(!t.length)return null;t.pop()}else t.push(i);return t.join("/")}function WN(n,e){return t=>{if(!t)return null;if(t.startsWith("#"))return{kind:"doc",slug:e,hash:U_(t.slice(1))};if(/^(https?:\/\/|mailto:)/i.test(t))return{kind:"external",href:t};if(/^[a-z][a-z0-9+.-]*:/i.test(t)||t.startsWith("//"))return null;const[i,a=""]=t.split("#"),s=VN(n,i);if(s===null)return null;const o=qN[s];return o?{kind:"doc",slug:o,hash:U_(a)}:s?{kind:"external",href:O_+s.split("/").map(encodeURIComponent).join("/")}:null}}function U_(n){try{return decodeURIComponent(n)}catch{return n}}function F_(n){const e=new Map,t=(a,s,o=0)=>{const r={link:WN(s,n),slugs:e,dropH1:!0},l=IN(a,r);return o?l.replace(/<(\/?)h([1-6])\b/g,(c,p,h)=>`<${p}h${Math.min(6,Number(h)+o)}`):l},i=a=>s=>P_(a,L_(s,e),b(s));return{slugs:e,h2:i(2),h3:i(3),md:t}}const Wt=n=>`<p>${n}</p>`,Et=n=>`<code>${b(n)}</code>`,el=(n,e,t="")=>`<a href="/docs/${n}${t?"#"+t:""}" data-doc="${n}" data-hash="${b(t)}">${b(e)}</a>`,B_=n=>`<a href="/agents#connect">${b(n)}</a>`,jc=(n,e)=>`<a href="${b(ri[n].path)}" data-app="${b(n)}">${b(e)}</a>`;function H_(n){return`<ol class="dc-steps">${n.map(([e,t])=>`<li><b>${b(e)}</b><div>${t}</div></li>`).join("")}</ol>`}function XN(n){return`<div class="dc-cards">${n.map(([e,t,i])=>`<a class="dc-card" href="/docs/${e}" data-doc="${e}" data-hash=""><b>${b(t)}</b><span>${b(i)}</span></a>`).join("")}</div>`}function G_(n,e){return`<div class="dc-table"><table><thead><tr>${n.map(t=>`<th>${b(t)}</th>`).join("")}</tr></thead><tbody>${e.map(t=>`<tr>${t.map(i=>`<td>${i}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`}const q_=(n,e)=>`<div class="dc-prompt">${$o(n,"",e)}</div>`,V_=()=>/mac|iphone|ipad/i.test(navigator.platform||navigator.userAgent),Mt=(...n)=>`<span class="dc-keys">${n.map(e=>`<kbd>${b(e)}</kbd>`).join("")}</span>`;function KN(){return location.origin+"/mcp"}function YN(n){return n.h2("What Memora is")+Wt("Memora is long-term memory for your AI agents, on your own server. Every memory is a plain Markdown note in a folder you own (the <b>vault</b>), with <code>[[wikilinks]]</code>, <code>#tags</code> and full git history.")+`<ul>
10310
+ `,O_="https://github.com/Codrihub/memora"+"/blob/main/",qN={"README.md":"get-started","docs/INSTALL.md":"install","docs/CONFIGURATION.md":"configuration","docs/MCP.md":"mcp","docs/API.md":"api","docs/DEPLOYMENT.md":"deployment","docs/ARCHITECTURE.md":"architecture","docs/DATABASE.md":"database","docs/contracts/tools-permissions.md":"tool-reference","SECURITY.md":"security","CHANGELOG.md":"changelog"};function VN(n,e){const t=n.split("/").slice(0,-1);for(const i of e.split("/"))if(!(i===""||i==="."))if(i===".."){if(!t.length)return null;t.pop()}else t.push(i);return t.join("/")}function WN(n,e){return t=>{if(!t)return null;if(t.startsWith("#"))return{kind:"doc",slug:e,hash:U_(t.slice(1))};if(/^(https?:\/\/|mailto:)/i.test(t))return{kind:"external",href:t};if(/^[a-z][a-z0-9+.-]*:/i.test(t)||t.startsWith("//"))return null;const[i,a=""]=t.split("#"),s=VN(n,i);if(s===null)return null;const o=qN[s];return o?{kind:"doc",slug:o,hash:U_(a)}:s?{kind:"external",href:O_+s.split("/").map(encodeURIComponent).join("/")}:null}}function U_(n){try{return decodeURIComponent(n)}catch{return n}}function F_(n){const e=new Map,t=(a,s,o=0)=>{const r={link:WN(s,n),slugs:e,dropH1:!0},l=IN(a,r);return o?l.replace(/<(\/?)h([1-6])\b/g,(c,p,h)=>`<${p}h${Math.min(6,Number(h)+o)}`):l},i=a=>s=>P_(a,L_(s,e),b(s));return{slugs:e,h2:i(2),h3:i(3),md:t}}const Wt=n=>`<p>${n}</p>`,Mt=n=>`<code>${b(n)}</code>`,el=(n,e,t="")=>`<a href="/docs/${n}${t?"#"+t:""}" data-doc="${n}" data-hash="${b(t)}">${b(e)}</a>`,B_=n=>`<a href="/agents#connect">${b(n)}</a>`,jc=(n,e)=>`<a href="${b(ri[n].path)}" data-app="${b(n)}">${b(e)}</a>`;function H_(n){return`<ol class="dc-steps">${n.map(([e,t])=>`<li><b>${b(e)}</b><div>${t}</div></li>`).join("")}</ol>`}function XN(n){return`<div class="dc-cards">${n.map(([e,t,i])=>`<a class="dc-card" href="/docs/${e}" data-doc="${e}" data-hash=""><b>${b(t)}</b><span>${b(i)}</span></a>`).join("")}</div>`}function G_(n,e){return`<div class="dc-table"><table><thead><tr>${n.map(t=>`<th>${b(t)}</th>`).join("")}</tr></thead><tbody>${e.map(t=>`<tr>${t.map(i=>`<td>${i}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`}const q_=(n,e)=>`<div class="dc-prompt">${$o(n,"",e)}</div>`,V_=()=>/mac|iphone|ipad/i.test(navigator.platform||navigator.userAgent),At=(...n)=>`<span class="dc-keys">${n.map(e=>`<kbd>${b(e)}</kbd>`).join("")}</span>`;function KN(){return location.origin+"/mcp"}function YN(n){return n.h2("What Memora is")+Wt("Memora is long-term memory for your AI agents, on your own server. Every memory is a plain Markdown note in a folder you own (the <b>vault</b>), with <code>[[wikilinks]]</code>, <code>#tags</code> and full git history.")+`<ul>
10232
10311
  <li><b>Agents</b> read and write the vault over the Model Context Protocol (MCP), each with its own API key or an OAuth approval.</li>
10233
10312
  <li><b>You</b> browse, edit and govern it here: the brain and graph views, the node editor, live activity, keys, tool switches and access rules.</li>
10234
10313
  <li><b>One process</b> serves the web UI, the HTTP API, MCP and realtime updates on a single port, with server state in one SQLite file.</li>
10235
- </ul>`+n.h2("First run")+Wt("Four steps take a fresh server to an agent that remembers.")+H_([["Install Memora",Wt("On a Linux server with systemd, anywhere with Docker, or with npm on Linux. Every other option is in "+el("install","Install")+".")+$o(`curl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh
10314
+ </ul>`+n.h2("First run")+Wt("Four steps take a fresh server to an agent that remembers.")+H_([["Install Memora",Wt("With npm, Docker or the native installer, in that order of ease. Every other option is in "+el("install","Install")+".")+$o(`# npm (Linux x86_64 / arm64, Node 18+), then keep it running
10315
+ npm install -g @codrihub/memora && memora
10236
10316
 
10237
- # or with Docker
10317
+ # Docker
10238
10318
  docker run -d --name memora --restart unless-stopped -p 8400:8400 \\
10239
10319
  -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest
10240
10320
 
10241
- # or with npm (Linux x86_64 / arm64, Node 18+), then run memora
10242
- npm install -g @codrihub/memora`,"bash")],["Get a one-time code",Wt(`Run ${Et("sudo memora-cli setup --minutes 15")} (Docker: ${Et("docker exec -it memora memora-cli setup --minutes 15")}). It prints a one-time code and the link to open. Open it, enter the code and create the owner account.`)],["Choose the vault",Wt(`Pick the folder that holds your notes (${Et("/var/lib/memora/vault")} natively, ${Et("/data")} in Docker). An existing folder of Markdown works as is. You can switch it later in ${jc("settings","Settings")}.`)],["Connect an agent",Wt(`Open the ${B_("connect wizard")} (Agents & API keys → Connect), pick the app and copy its config. Then paste the ${el("agent-instructions","agent instructions")} so the agent knows when to recall and when to remember.`)]])+Yc("note","Setup window",Wt(`If a setup window expires unused, the instance locks until you run ${Et("memora-cli setup")} or ${Et("memora-cli unlock")} on the server.`))+n.h2("Where to next")+XN([["agent-instructions","Agent instructions","The recommended prompt and where to paste it."],["connect","Connect an agent","MCP URL, keys and client configs."],["tool-reference","Tool reference","Every MCP tool this server offers."],["configuration","Configuration","Every setting and where it lives."],["deployment","Deployment","TLS, reverse proxies and hardening."],["security","Security & privacy","The security model and how to report issues."]])+n.md(ru(lu,"Features"),"README.md")+n.md(ru(lu,"Project layout"),"README.md")+n.md(ru(lu,"Versioning"),"README.md")}function jN(n){const e=[["Claude (claude.ai and Claude Desktop)","In a project: <b>Project instructions</b>. For every chat: Settings → Profile → personal preferences.","Full in a project, short in preferences"],["ChatGPT","In a project: the project <b>Instructions</b>. For every chat: Settings → Personalization → <b>Custom instructions</b>.","Full in a project, short in custom instructions"],["Claude Code",`${Et("CLAUDE.md")} in the project root, or ${Et("~/.claude/CLAUDE.md")} for every project.`,"Full"],["Cursor",`A project rule in ${Et(".cursor/rules/")} (for example ${Et(".cursor/rules/memora.mdc")}), or Cursor Settings → Rules → <b>User Rules</b> for every project.`,"Full"],["VS Code (GitHub Copilot)",`${Et(".github/copilot-instructions.md")} in the repository.`,"Full"],["Codex CLI",`${Et("AGENTS.md")} in the repository, or ${Et("~/.codex/AGENTS.md")} for every project.`,"Full"],["Gemini CLI",`${Et("GEMINI.md")} in the project root, or ${Et("~/.gemini/GEMINI.md")} for every project.`,"Full"],["Windsurf",`Customizations → <b>Rules</b>: a global rule, or a workspace rule in ${Et(".windsurf/rules/")}.`,"Full"]];return Wt("Connecting an agent gives it the tools; these instructions tell it when to use them. Paste them once per client and the agent searches Memora before it answers and saves what is worth keeping.")+Yc("note","Connect first",Wt(`The prompt assumes the MCP server is named ${Et("memora")} and connected. See ${el("connect","Connect an agent")}.`))+n.h2("Full instructions")+Wt("For a system prompt, project instructions or a rules file.")+q_(um,"Full prompt")+n.h2("Short version")+Wt("One paragraph for clients with a small instructions field.")+q_(s1,"Short prompt")+n.h2("Where to paste it")+G_(["Client","Where","Version"],e.map(([t,i,a])=>[`<b>${b(t)}</b>`,i,b(a)]))+n.h3("Cursor rule file")+Wt(`A rule in ${Et(".cursor/rules/")} applies to every chat when its header sets ${Et("alwaysApply: true")}:`)+$o(`---
10321
+ # Native installer (Linux server with systemd)
10322
+ curl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh`,"bash")],["Get a one-time code",Wt(`Run ${Mt("memora-cli setup --minutes 15")} (Docker: ${Mt("docker exec -it memora memora-cli setup --minutes 15")}, native: ${Mt("sudo memora-cli setup --minutes 15")}). It prints a one-time code and the link to open. Open it, enter the code and create the owner account.`)],["Choose the vault",Wt(`Pick the folder that holds your notes (${Mt("/var/lib/memora/vault")} natively, ${Mt("/data")} in Docker). An existing folder of Markdown works as is. You can switch it later in ${jc("settings","Settings")}.`)],["Connect an agent",Wt(`Open the ${B_("connect wizard")} (Agents & API keys → Connect), pick the app and copy its config. Then paste the ${el("agent-instructions","agent instructions")} so the agent knows when to recall and when to remember.`)]])+Yc("note","Setup window",Wt(`If a setup window expires unused, the instance locks until you run ${Mt("memora-cli setup")} or ${Mt("memora-cli unlock")} on the server.`))+n.h2("Where to next")+XN([["agent-instructions","Agent instructions","The recommended prompt and where to paste it."],["connect","Connect an agent","MCP URL, keys and client configs."],["tool-reference","Tool reference","Every MCP tool this server offers."],["configuration","Configuration","Every setting and where it lives."],["deployment","Deployment","TLS, reverse proxies and hardening."],["security","Security & privacy","The security model and how to report issues."]])+n.md(ru(lu,"Features"),"README.md")+n.md(ru(lu,"Project layout"),"README.md")+n.md(ru(lu,"Versioning"),"README.md")}function jN(n){const e=[["Claude (claude.ai and Claude Desktop)","In a project: <b>Project instructions</b>. For every chat: Settings → Profile → personal preferences.","Full in a project, short in preferences"],["ChatGPT","In a project: the project <b>Instructions</b>. For every chat: Settings → Personalization → <b>Custom instructions</b>.","Full in a project, short in custom instructions"],["Claude Code",`${Mt("CLAUDE.md")} in the project root, or ${Mt("~/.claude/CLAUDE.md")} for every project.`,"Full"],["Cursor",`A project rule in ${Mt(".cursor/rules/")} (for example ${Mt(".cursor/rules/memora.mdc")}), or Cursor Settings → Rules → <b>User Rules</b> for every project.`,"Full"],["VS Code (GitHub Copilot)",`${Mt(".github/copilot-instructions.md")} in the repository.`,"Full"],["Codex CLI",`${Mt("AGENTS.md")} in the repository, or ${Mt("~/.codex/AGENTS.md")} for every project.`,"Full"],["Gemini CLI",`${Mt("GEMINI.md")} in the project root, or ${Mt("~/.gemini/GEMINI.md")} for every project.`,"Full"],["Windsurf",`Customizations → <b>Rules</b>: a global rule, or a workspace rule in ${Mt(".windsurf/rules/")}.`,"Full"]];return Wt("Connecting an agent gives it the tools; these instructions tell it when to use them. Paste them once per client and the agent searches Memora before it answers and saves what is worth keeping.")+Yc("note","Connect first",Wt(`The prompt assumes the MCP server is named ${Mt("memora")} and connected. See ${el("connect","Connect an agent")}.`))+n.h2("Full instructions")+Wt("For a system prompt, project instructions or a rules file.")+q_(um,"Full prompt")+n.h2("Short version")+Wt("One paragraph for clients with a small instructions field.")+q_(s1,"Short prompt")+n.h2("Where to paste it")+G_(["Client","Where","Version"],e.map(([t,i,a])=>[`<b>${b(t)}</b>`,i,b(a)]))+n.h3("Cursor rule file")+Wt(`A rule in ${Mt(".cursor/rules/")} applies to every chat when its header sets ${Mt("alwaysApply: true")}:`)+$o(`---
10243
10323
  description: Use Memora as long-term memory
10244
10324
  alwaysApply: true
10245
10325
  ---
10246
10326
 
10247
10327
  `+um,"markdown",".cursor/rules/memora.mdc")+n.h2("Tips")+`<ul>
10248
- <li>In a file such as ${Et("CLAUDE.md")} or ${Et("AGENTS.md")} that already has content, add the text under its own heading, for example ${Et("## Memory")}.</li>
10249
- <li>The prompt names tools such as ${Et("search_memory")}, ${Et("read_memory")} and ${Et("patch_memory")}. If you switch tools off on ${jc("tools","Tools")} or narrow a key, adjust the text to match.</li>
10328
+ <li>In a file such as ${Mt("CLAUDE.md")} or ${Mt("AGENTS.md")} that already has content, add the text under its own heading, for example ${Mt("## Memory")}.</li>
10329
+ <li>The prompt names tools such as ${Mt("search_memory")}, ${Mt("read_memory")} and ${Mt("patch_memory")}. If you switch tools off on ${jc("tools","Tools")} or narrow a key, adjust the text to match.</li>
10250
10330
  <li>Every agent that shares the vault should get the same instructions, so they write notes the same way.</li>
10251
- </ul>`}function ZN(n){const e=KN();return Wt("Agents reach Memora over MCP at one URL. Each agent gets its own API key, or connects with OAuth after you approve it in the browser.")+n.h2("This server")+$o(e,"","MCP URL")+Wt(`Behind a reverse proxy, use the public URL (the one set in ${Et("MEMORA_BASE_URL")}). Requests for any other host than ${Et("MEMORA_DOMAIN")} get 404.`)+n.h2("Steps")+H_([["Open Agents & API keys",Wt(`Open the ${B_("connect wizard")} on Agents & API keys.`)],["Pick the app",Wt("Claude, ChatGPT, Claude Code, Cursor, VS Code, Codex and others each get ready-made steps.")],["Create the key and copy the config",Wt("The raw key is shown once. Give each agent its own key so you can see, limit and revoke it on its own.")],["Add the instructions",Wt(`Paste the ${el("agent-instructions","agent instructions")} into the client.`)]])+`<p><a class="btn primary dc-btn" href="${b(ri.keys.path)}" data-app="keys">Open Agents &amp; API keys</a></p>`+n.h2("Quick configs")+n.h3("Claude Code")+$o(`claude mcp add --transport http memora ${e} \\
10252
- --header "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"`,"bash")+n.h3("Clients with an mcpServers config")+Wt(`Cursor, Windsurf and others. VS Code uses the key ${Et("servers")} in ${Et(".vscode/mcp.json")}.`)+$o(JSON.stringify({mcpServers:{memora:{type:"http",url:e,headers:{Authorization:"Bearer memora_live_REPLACE_WITH_YOUR_KEY"}}}},null,2),"json")+n.h3("OAuth")+Wt(`Clients that support MCP authorization (Claude and ChatGPT custom connectors, or Claude Code without ${Et("--header")}) need only the URL. You approve them in the browser and they show up as keys you can restrict or revoke.`)+Yc("tip","More clients",Wt(`Codex, stdio-only clients and testing from a shell are covered in ${el("mcp","MCP","connecting-an-agent")}.`))+n.h2("Limit what an agent can do")+`<ul>
10253
- <li><b>Scopes</b> on the key: ${Et("read")}, ${Et("write")}, ${Et("admin")}.</li>
10331
+ </ul>`}function ZN(n){const e=KN();return Wt("Agents reach Memora over MCP at one URL. Each agent gets its own API key, or connects with OAuth after you approve it in the browser.")+n.h2("This server")+$o(e,"","MCP URL")+Wt(`Behind a reverse proxy, use the public URL (the one set in ${Mt("MEMORA_BASE_URL")}). Requests for any other host than ${Mt("MEMORA_DOMAIN")} get 404.`)+n.h2("Steps")+H_([["Open Agents & API keys",Wt(`Open the ${B_("connect wizard")} on Agents & API keys.`)],["Pick the app",Wt("Claude, ChatGPT, Claude Code, Cursor, VS Code, Codex and others each get ready-made steps.")],["Create the key and copy the config",Wt("The raw key is shown once. Give each agent its own key so you can see, limit and revoke it on its own.")],["Add the instructions",Wt(`Paste the ${el("agent-instructions","agent instructions")} into the client.`)]])+`<p><a class="btn primary dc-btn" href="${b(ri.keys.path)}" data-app="keys">Open Agents &amp; API keys</a></p>`+n.h2("Quick configs")+n.h3("Claude Code")+$o(`claude mcp add --transport http memora ${e} \\
10332
+ --header "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"`,"bash")+n.h3("Clients with an mcpServers config")+Wt(`Cursor, Windsurf and others. VS Code uses the key ${Mt("servers")} in ${Mt(".vscode/mcp.json")}.`)+$o(JSON.stringify({mcpServers:{memora:{type:"http",url:e,headers:{Authorization:"Bearer memora_live_REPLACE_WITH_YOUR_KEY"}}}},null,2),"json")+n.h3("OAuth")+Wt(`Clients that support MCP authorization (Claude and ChatGPT custom connectors, or Claude Code without ${Mt("--header")}) need only the URL. You approve them in the browser and they show up as keys you can restrict or revoke.`)+Yc("tip","More clients",Wt(`Codex, stdio-only clients and testing from a shell are covered in ${el("mcp","MCP","connecting-an-agent")}.`))+n.h2("Limit what an agent can do")+`<ul>
10333
+ <li><b>Scopes</b> on the key: ${Mt("read")}, ${Mt("write")}, ${Mt("admin")}.</li>
10254
10334
  <li><b>Tool lists</b> per key, and server-wide switches on ${jc("tools","Tools")}.</li>
10255
10335
  <li><b>Privacy rules</b> that hide notes or folders from chosen agents.</li>
10256
10336
  <li><b>Access rules</b> by IP, range and domain on ${jc("access","Access rules")}.</li>
10257
- </ul>`+Wt(`Details: ${el("tool-reference","Tool reference","switches-and-permissions")}.`)}function JN(n){const e=V_()?"⌘":"Ctrl",t=V_()?"⌥":"Alt",i=s=>G_(["Keys","Action"],s.map(([o,r])=>[o,b(r)])),a=Gi.slice(0,9).map((s,o)=>[Mt(t,String(o+1)),ri[s].label]);return Wt("Shortcuts work anywhere outside a text field unless noted. On a Mac, Ctrl is ⌘ and Alt is ⌥.")+n.h2("Everywhere")+i([[Mt(e,"K"),"Search nodes, jump to pages, run actions"],[Mt("/"),"Open search"],[Mt("?"),"Help & shortcuts"],[Mt("["),"Collapse or expand the sidebar"],[Mt("Esc"),"Close a dialog, menu or panel"]])+n.h2("Pages")+i(a)+n.h2("Search")+i([[Mt(">"),"Typed first: actions only (new node, theme ...)"],[Et("tag:name"),"Narrow results by tag"],[Mt("↑")+Mt("↓"),"Move through results"],[Mt("Enter"),"Open the result"]])+n.h2("Nodes")+i([[Mt("N"),"New node in the open folder"],[Mt("E"),"Edit the open node"],[Mt(e,"E"),"Switch between reading and editing"],[Mt("P"),"Pin or unpin the node"],[Mt("M"),"Move the node"],[Mt("F2"),"Rename the node"],[Mt("Delete"),"Delete the node"]])+n.h2("Editor")+i([[Mt(e,"S"),"Save now"],[Mt(e,"B"),"Bold"],[Mt(e,"I"),"Italic"],[Mt(e,"K"),"Link"],[Mt(e,"`"),"Inline code"],[Mt(e,t,"H"),"Heading"],[Mt(e,"Shift","8"),"Bullet list"],[Mt(e,"Shift","9"),"Task list"],[Mt("Tab")+Mt("Shift","Tab"),"Indent or outdent"],[Mt("Esc"),"Back to reading"]])+n.h2("Graph")+i([[Mt("/"),"Find a node"],[Mt("F"),"Fit everything in view"],[Mt("1")+Mt("2")+Mt("3"),"Force, radial or cluster layout"],[Mt("P"),"Pin the selected node"],[Mt("Esc"),"Close the card and panels"]])}function QN(n){return Wt(`Every MCP tool this server offers, read live from the server, grouped as on ${jc("tools","Tools")}. Agents call a tool by the name in code. Tools that are switched off are hidden from agents.`)+`<div class="dc-legend">${os("read")}${os("write")}${os("admin")}</div><div id="dcTools" class="dc-tools" aria-busy="true"><p class="dc-muted">Loading the tool catalog…</p></div>`+n.h2("Switches and permissions")+n.md(BN,"docs/contracts/tools-permissions.md",1)}async function eD(n,e){const t=n.querySelector("#dcTools");if(!t)return;let i="";try{const a=await gu(),s=a.filter(o=>!o.enabled).length;i=Wt(`${a.length} tools${s?`, ${s} switched off on this server`:""}.`)+mm(a).map(([o,r])=>e.h2(oo(o))+(Yl(o)?Wt(b(Yl(o))):"")+`<div class="dc-toolrows">${r.map(l=>`<div class="dc-tool${l.enabled?"":" off"}" id="tool-${b(l.name)}">
10337
+ </ul>`+Wt(`Details: ${el("tool-reference","Tool reference","switches-and-permissions")}.`)}function JN(n){const e=V_()?"⌘":"Ctrl",t=V_()?"⌥":"Alt",i=s=>G_(["Keys","Action"],s.map(([o,r])=>[o,b(r)])),a=Gi.slice(0,9).map((s,o)=>[At(t,String(o+1)),ri[s].label]);return Wt("Shortcuts work anywhere outside a text field unless noted. On a Mac, Ctrl is ⌘ and Alt is ⌥.")+n.h2("Everywhere")+i([[At(e,"K"),"Search nodes, jump to pages, run actions"],[At("/"),"Open search"],[At("?"),"Help & shortcuts"],[At("["),"Collapse or expand the sidebar"],[At("Esc"),"Close a dialog, menu or panel"]])+n.h2("Pages")+i(a)+n.h2("Search")+i([[At(">"),"Typed first: actions only (new node, theme ...)"],[Mt("tag:name"),"Narrow results by tag"],[At("↑")+At("↓"),"Move through results"],[At("Enter"),"Open the result"]])+n.h2("Nodes")+i([[At("N"),"New node in the open folder"],[At("E"),"Edit the open node"],[At(e,"E"),"Switch between reading and editing"],[At("P"),"Pin or unpin the node"],[At("M"),"Move the node"],[At("F2"),"Rename the node"],[At("Delete"),"Delete the node"]])+n.h2("Editor")+i([[At(e,"S"),"Save now"],[At(e,"B"),"Bold"],[At(e,"I"),"Italic"],[At(e,"K"),"Link"],[At(e,"`"),"Inline code"],[At(e,t,"H"),"Heading"],[At(e,"Shift","8"),"Bullet list"],[At(e,"Shift","9"),"Task list"],[At("Tab")+At("Shift","Tab"),"Indent or outdent"],[At("Esc"),"Back to reading"]])+n.h2("Graph")+i([[At("/"),"Find a node"],[At("F"),"Fit everything in view"],[At("1")+At("2")+At("3"),"Force, radial or cluster layout"],[At("P"),"Pin the selected node"],[At("Esc"),"Close the card and panels"]])}function QN(n){return Wt(`Every MCP tool this server offers, read live from the server, grouped as on ${jc("tools","Tools")}. Agents call a tool by the name in code. Tools that are switched off are hidden from agents.`)+`<div class="dc-legend">${os("read")}${os("write")}${os("admin")}</div><div id="dcTools" class="dc-tools" aria-busy="true"><p class="dc-muted">Loading the tool catalog…</p></div>`+n.h2("Switches and permissions")+n.md(BN,"docs/contracts/tools-permissions.md",1)}async function eD(n,e){const t=n.querySelector("#dcTools");if(!t)return;let i="";try{const a=await gu(),s=a.filter(o=>!o.enabled).length;i=Wt(`${a.length} tools${s?`, ${s} switched off on this server`:""}.`)+mm(a).map(([o,r])=>e.h2(oo(o))+(Yl(o)?Wt(b(Yl(o))):"")+`<div class="dc-toolrows">${r.map(l=>`<div class="dc-tool${l.enabled?"":" off"}" id="tool-${b(l.name)}">
10258
10338
  <div class="dc-tool-h"><code>${b(l.name)}</code><span class="dc-tool-t">${b(Kl(l.name))}</span>${os(or(l))}${l.enabled?"":'<span class="badge">Off</span>'}</div>
10259
10339
  ${l.description?`<div class="dc-tool-d">${No(l.description,{link:()=>null,slugs:e.slugs})}</div>`:""}
10260
10340
  </div>`).join("")}</div>`).join("")}catch{i=Yc("warning","Could not load the tools",Wt('The server did not answer. The public catalog is at <a href="/tools" target="_blank" rel="noopener">/tools</a>.'))}t.isConnected&&(t.innerHTML=i,t.removeAttribute("aria-busy"))}const tD=(n,...e)=>e.map(t=>ru(n,t)).join(`