infernoflow 0.44.15 β†’ 0.44.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,6 +37,17 @@ Bookmarks are **never auto-pruned**, and they surface in `infernoflow switch` un
37
37
 
38
38
  ---
39
39
 
40
+ ## πŸ†• Proactive capture β€” a Claude skill + a memory-keeper agent
41
+
42
+ `init` now installs two things into `.claude/` so the loop runs itself on Claude Code:
43
+
44
+ - **`infernoflow-memory` skill** (`.claude/skills/`) β€” teaches the agent to start warm (`recap`), then proactively `log` real gotchas, decisions-with-a-*because*, dead ends, and durable preferences, and drop a `bookmark` at stopping points or when you say *"bookmark this"*. Capture is **balanced** β€” it skips routine steps, anything obvious from the code, secrets, and duplicates.
45
+ - **`memory-keeper` subagent** (`.claude/agents/`) β€” a specialist you can delegate to. It sweeps the session, dedupes against what's already stored, logs what's worth keeping, drops bookmarks, and reports back. It never edits code or logs secrets.
46
+
47
+ Both are installed automatically by `infernoflow init` (fresh **and** on re-run of an existing project) and ship in the package β€” nothing to set up by hand.
48
+
49
+ ---
50
+
40
51
  ## The loop
41
52
 
42
53
  Every new AI session today starts cold. The agent re-reads your code, re-derives the obvious, and re-makes the same wrong move someone else made yesterday. infernoflow closes that loop in four stages:
@@ -59,7 +70,7 @@ infernoflow init --yes
59
70
 
60
71
  Zero runtime dependencies. Works on Node β‰₯ 18 β€” macOS, Linux, Windows.
61
72
 
62
- `init --yes` does the whole setup: creates `.ai-memory/`, writes rule files for every supported IDE, wires the MCP server for Cursor / VS Code Copilot / Claude Code in one shot, applies the clean-tree git policy, and drops a visible demo entry so you can confirm the loop is alive with:
73
+ `init --yes` does the whole setup: creates `.ai-memory/`, writes rule files for every supported IDE, wires the MCP server for Cursor / VS Code Copilot / Claude Code in one shot, installs the `infernoflow-memory` skill + `memory-keeper` agent into `.claude/`, applies the clean-tree git policy, and drops a visible demo entry so you can confirm the loop is alive with:
63
74
 
64
75
  ```bash
65
76
  infernoflow status
@@ -0,0 +1 @@
1
+ import*as r from"node:fs";import*as n from"node:path";import{fileURLToPath as m}from"node:url";const f=n.dirname(m(import.meta.url));function l(){return n.resolve(f,"../templates")}const c=new Set;function p(e){return r.existsSync(n.join(e,".ai-memory"))||r.existsSync(n.join(e,"inferno"))}function a(e,i){if(!r.existsSync(e))return 0;let t=0;for(const s of r.readdirSync(e,{withFileTypes:!0})){const u=n.join(e,s.name),o=n.join(i,s.name);if(s.isDirectory()){t+=a(u,o);continue}r.existsSync(o)||(r.mkdirSync(n.dirname(o),{recursive:!0}),r.copyFileSync(u,o),t++)}return t}function d(e){try{if(!e||c.has(e)||(c.add(e),!p(e)))return 0;const i=l();let t=0;return t+=a(n.join(i,"skills"),n.join(e,".claude","skills")),t+=a(n.join(i,"agents"),n.join(e,".claude","agents")),t}catch{return 0}}export{d as ensureClaudeAssets};
@@ -1,11 +1,11 @@
1
- import*as i from"node:fs";import*as s from"node:path";import*as H from"node:readline";import{fileURLToPath as de}from"node:url";import{header as ue,ok as g,warn as T,info as q,done as z,nextSteps as me,bold as J,cyan as f,yellow as G,gray as v}from"../ui/output.mjs";import{discoverProjectSignals as M,reviewCapabilitiesInteractive as ye,writeAdoptionBaseline as ge,buildAdoptionReport as he,summarizeCapabilities as we,buildSignalsReport as ke}from"./adopt.mjs";import{installCursorHooksArtifacts as je}from"../cursorHooksInstall.mjs";import{ensureAmpDir as Se,appendEntry as V,writeDefaultConfig as ve}from"../amp/io.mjs";import{applyCleanTreePolicy as X}from"../cleanTree.mjs";import{installVsCodeCopilotHooksArtifacts as be}from"../vsCodeCopilotHooksInstall.mjs";import{writeInitRuleFiles as B}from"../ruleFiles.mjs";import{autoSetupMcp as Z}from"./setup.mjs";const Ce=s.dirname(de(import.meta.url));function Oe(){return s.resolve(Ce,"../../templates")}function L(e,o,n=""){return new Promise(t=>{const r=n?v(` (${n})`):"";e.question(` ${o}${r}: `,c=>{t(c.trim()||n)})})}function W(e,...o){for(const n of o){const t=e.indexOf(n);if(t!==-1&&e[t+1]&&!e[t+1].startsWith("-"))return e[t+1]}return null}function U(e,o,n,t=!1){return i.existsSync(o)&&!n?(t||T("Skipped (exists): "+s.relative(process.cwd(),o)),!1):(i.mkdirSync(s.dirname(o),{recursive:!0}),i.copyFileSync(e,o),t||g("Created: "+f(s.relative(process.cwd(),o))),!0)}function xe(e,o,n){i.mkdirSync(o,{recursive:!0});for(const t of i.readdirSync(e,{withFileTypes:!0})){const r=s.join(e,t.name),c=s.join(o,t.name);t.isDirectory()?xe(r,c,n):U(r,c,n)}}function Ie(e,o=!1){const n=s.join(e,"package.json");if(!i.existsSync(n))return;const t=JSON.parse(i.readFileSync(n,"utf8"));t.scripts=t.scripts||{};let r=!1;const c={"inferno:check":"infernoflow check","inferno:status":"infernoflow status","inferno:gate":"infernoflow doc-gate","inferno:impact":"infernoflow pr-impact --json","inferno:sync":"infernoflow sync --auto --json","inferno:run":'infernoflow run "sync check" --provider auto --json',"inferno:hooks":"node scripts/inferno-install-hooks.mjs"};for(const[m,j]of Object.entries(c))t.scripts[m]||(t.scripts[m]=j,r=!0);r&&(i.writeFileSync(n,JSON.stringify(t,null,2)+`
2
- `,"utf8"),o||g("Updated "+f("package.json")+" scripts"))}const Q="# --- infernoflow (developer-local AI memory; do not commit) ---",Ae="# --- /infernoflow ---",ee=[".ai-memory/",".cursorrules","CLAUDE.md",".github/copilot-instructions.md"];function Qe(e,{silent:o=!1}={}){const n=s.join(e,".gitignore");let t="";if(i.existsSync(n)&&(t=i.readFileSync(n,"utf8")),t.includes(Q))return!1;const r=["",Q,"# Memory is per-developer, not per-branch. These files travel with you, not with git.",...ee,Ae,""].join(`
3
- `),c=t.length===0||t.endsWith(`
1
+ import*as n from"node:fs";import*as i from"node:path";import*as H from"node:readline";import{fileURLToPath as ye}from"node:url";import{header as ge,ok as w,warn as T,info as z,done as V,nextSteps as he,bold as J,cyan as f,yellow as G,gray as v}from"../ui/output.mjs";import{discoverProjectSignals as M,reviewCapabilitiesInteractive as we,writeAdoptionBaseline as ke,buildAdoptionReport as je,summarizeCapabilities as Se,buildSignalsReport as ve}from"./adopt.mjs";import{installCursorHooksArtifacts as be}from"../cursorHooksInstall.mjs";import{ensureAmpDir as Ce,appendEntry as X,writeDefaultConfig as xe}from"../amp/io.mjs";import{applyCleanTreePolicy as B}from"../cleanTree.mjs";import{installVsCodeCopilotHooksArtifacts as Oe}from"../vsCodeCopilotHooksInstall.mjs";import{writeInitRuleFiles as Z}from"../ruleFiles.mjs";import{autoSetupMcp as Q}from"./setup.mjs";const Ie=i.dirname(ye(import.meta.url));function W(){return i.resolve(Ie,"../../templates")}function L(e,o,t=""){return new Promise(s=>{const r=t?v(` (${t})`):"";e.question(` ${o}${r}: `,l=>{s(l.trim()||t)})})}function Y(e,...o){for(const t of o){const s=e.indexOf(t);if(s!==-1&&e[s+1]&&!e[s+1].startsWith("-"))return e[s+1]}return null}function U(e,o,t,s=!1){return n.existsSync(o)&&!t?(s||T("Skipped (exists): "+i.relative(process.cwd(),o)),!1):(n.mkdirSync(i.dirname(o),{recursive:!0}),n.copyFileSync(e,o),s||w("Created: "+f(i.relative(process.cwd(),o))),!0)}function Ae(e,o,t){n.mkdirSync(o,{recursive:!0});for(const s of n.readdirSync(e,{withFileTypes:!0})){const r=i.join(e,s.name),l=i.join(o,s.name);s.isDirectory()?Ae(r,l,t):U(r,l,t)}}function ee(e,o){const t=i.join(W(),"skills");if(!n.existsSync(t))return 0;let s=0;const r=(l,d)=>{n.mkdirSync(d,{recursive:!0});for(const y of n.readdirSync(l,{withFileTypes:!0})){const a=i.join(l,y.name),u=i.join(d,y.name);if(y.isDirectory()){r(a,u);continue}n.existsSync(u)&&!o||(n.mkdirSync(i.dirname(u),{recursive:!0}),n.copyFileSync(a,u),s++,w("Created: "+f(i.relative(e,u))))}};return r(t,i.join(e,".claude","skills")),s}function oe(e,o){const t=i.join(W(),"agents");if(!n.existsSync(t))return 0;let s=0;const r=(l,d)=>{n.mkdirSync(d,{recursive:!0});for(const y of n.readdirSync(l,{withFileTypes:!0})){const a=i.join(l,y.name),u=i.join(d,y.name);if(y.isDirectory()){r(a,u);continue}n.existsSync(u)&&!o||(n.mkdirSync(i.dirname(u),{recursive:!0}),n.copyFileSync(a,u),s++,w("Created: "+f(i.relative(e,u))))}};return r(t,i.join(e,".claude","agents")),s}function Te(e,o=!1){const t=i.join(e,"package.json");if(!n.existsSync(t))return;const s=JSON.parse(n.readFileSync(t,"utf8"));s.scripts=s.scripts||{};let r=!1;const l={"inferno:check":"infernoflow check","inferno:status":"infernoflow status","inferno:gate":"infernoflow doc-gate","inferno:impact":"infernoflow pr-impact --json","inferno:sync":"infernoflow sync --auto --json","inferno:run":'infernoflow run "sync check" --provider auto --json',"inferno:hooks":"node scripts/inferno-install-hooks.mjs"};for(const[d,y]of Object.entries(l))s.scripts[d]||(s.scripts[d]=y,r=!0);r&&(n.writeFileSync(t,JSON.stringify(s,null,2)+`
2
+ `,"utf8"),o||w("Updated "+f("package.json")+" scripts"))}const ne="# --- infernoflow (developer-local AI memory; do not commit) ---",Ee="# --- /infernoflow ---",te=[".ai-memory/",".cursorrules","CLAUDE.md",".github/copilot-instructions.md"];function oo(e,{silent:o=!1}={}){const t=i.join(e,".gitignore");let s="";if(n.existsSync(t)&&(s=n.readFileSync(t,"utf8")),s.includes(ne))return!1;const r=["",ne,"# Memory is per-developer, not per-branch. These files travel with you, not with git.",...te,Ee,""].join(`
3
+ `),l=s.length===0||s.endsWith(`
4
4
  `)?"":`
5
- `;if(i.writeFileSync(n,t+c+r,"utf8"),!o){g("Updated "+f(".gitignore")+v(" \u2014 added entries:"));for(const m of ee)console.log(v(" + ")+f(m));console.log(v(" Memory + AI rule files are now per-developer (won't move with branches).")),console.log(v(" To commit them instead: delete the `")+f("# --- infernoflow ---")+v("` block in .gitignore."))}return!0}function K(e){const o=s.join(e,"package.json");if(i.existsSync(o))try{const n=JSON.parse(i.readFileSync(o,"utf8"));if(n.name)return n.name.replace(/[^a-z0-9_-]/gi,"_")}catch{}return s.basename(e)}function Te(e,o,n){const t={policyId:o,policyVersion:1,capabilities:n,rules:{docsRequiredOnCapabilityChange:!0,requireScenarioForEachCapability:!0,requireChangelogOnCapabilityChange:!0}};i.writeFileSync(e,JSON.stringify(t,null,2)+`
6
- `)}function Ee(e,o){const n={schemaVersion:1,capabilities:o.map(t=>({id:t,title:t.replace(/([A-Z])/g," $1").trim(),since:"0.1.0"}))};i.writeFileSync(e,JSON.stringify(n,null,2)+`
7
- `)}function Pe(e,o){i.mkdirSync(e,{recursive:!0});const n={scenarioId:"happy_path",description:"Basic happy-path flow covering all capabilities",capabilitiesCovered:o,steps:o.map(t=>({action:t,expect:`${t} works as expected`}))};i.writeFileSync(s.join(e,"happy_path.json"),JSON.stringify(n,null,2)+`
8
- `)}function oe(e,o){const n=`# Changelog \u2014 ${o}
5
+ `;if(n.writeFileSync(t,s+l+r,"utf8"),!o){w("Updated "+f(".gitignore")+v(" \u2014 added entries:"));for(const d of te)console.log(v(" + ")+f(d));console.log(v(" Memory + AI rule files are now per-developer (won't move with branches).")),console.log(v(" To commit them instead: delete the `")+f("# --- infernoflow ---")+v("` block in .gitignore."))}return!0}function K(e){const o=i.join(e,"package.json");if(n.existsSync(o))try{const t=JSON.parse(n.readFileSync(o,"utf8"));if(t.name)return t.name.replace(/[^a-z0-9_-]/gi,"_")}catch{}return i.basename(e)}function Pe(e,o,t){const s={policyId:o,policyVersion:1,capabilities:t,rules:{docsRequiredOnCapabilityChange:!0,requireScenarioForEachCapability:!0,requireChangelogOnCapabilityChange:!0}};n.writeFileSync(e,JSON.stringify(s,null,2)+`
6
+ `)}function Fe(e,o){const t={schemaVersion:1,capabilities:o.map(s=>({id:s,title:s.replace(/([A-Z])/g," $1").trim(),since:"0.1.0"}))};n.writeFileSync(e,JSON.stringify(t,null,2)+`
7
+ `)}function Ne(e,o){n.mkdirSync(e,{recursive:!0});const t={scenarioId:"happy_path",description:"Basic happy-path flow covering all capabilities",capabilitiesCovered:o,steps:o.map(s=>({action:s,expect:`${s} works as expected`}))};n.writeFileSync(i.join(e,"happy_path.json"),JSON.stringify(t,null,2)+`
8
+ `)}function ie(e,o){const t=`# Changelog \u2014 ${o}
9
9
 
10
10
  ## Unreleased
11
11
 
@@ -14,41 +14,41 @@ import*as i from"node:fs";import*as s from"node:path";import*as H from"node:read
14
14
  ## 0.1.0 \u2014 Initial release
15
15
 
16
16
  - Project initialized with infernoflow
17
- `;i.writeFileSync(e,n)}async function Ne(e,o){const{bold:n,cyan:t,gray:r,green:c,yellow:m,red:j}=await import("../ui/output.mjs");console.log(`
18
- `+n("\u{1F525} infernoflow init --lite")),console.log(" "+"\u2500".repeat(50)+`
19
- `),console.log(r(" Lite mode: 3 files, no scripts, no workflows, no hooks.")),console.log(r(" Use `infernoflow upgrade` later to expand to the full setup.\n"));const p=s.join(e,"inferno");i.existsSync(p)&&!o&&(console.log(m(` \u26A0 inferno/ already exists. Use --force to overwrite.
20
- `)),process.exit(0)),i.mkdirSync(p,{recursive:!0});const h=K(e);let S="";if(!process.argv.includes("--yes")&&!process.argv.includes("-y")&&process.stdin.isTTY){const E=H.createInterface({input:process.stdin,output:process.stdout});S=await new Promise(x=>{E.question(r(" What does this project do? (one line, Enter to skip): "),I=>{E.close(),x(I.trim())})})}const O={policyId:h,policyVersion:1,lite:!0,capabilities:[],intent:S||void 0};i.writeFileSync(s.join(p,"contract.json"),JSON.stringify(O,null,2)+`
21
- `),i.writeFileSync(s.join(p,"capabilities.json"),JSON.stringify([],null,2)+`
22
- `),i.writeFileSync(s.join(p,"sessions.jsonl"),"","utf8"),i.writeFileSync(s.join(p,".lite"),"1","utf8"),console.log(c(" \u2714 Created inferno/contract.json")),console.log(c(" \u2714 Created inferno/capabilities.json")),console.log(c(" \u2714 Created inferno/sessions.jsonl")),console.log(),console.log(" "+n("Ready. Start using it:")),console.log(" "+t("infernoflow log")+r(` "what you're building" --type note`)),console.log(" "+t("infernoflow context")+r(" \u2014 generate AI context to paste")),console.log(" "+t("infernoflow init --mode full")+r(" \u2014 expand to full setup when you need it")),console.log()}const Fe=/^(?:node|npm|npx|yarn|pnpm|bun|git|cd|mkdir|rm|ls|cat|echo|type|dir|copy|del|move|python|python3|pip|go|cargo|java|gradle|mvn|docker|kubectl|curl|wget|ssh|scp|chmod|chown|sudo|brew|apt|yum)\b/i,Re=/\s(?:&&|\|\||>>|>|<<|<|\|)\s/,_e=/(?:^|\s)[A-Za-z]:\\|\.\.[\\\/]|[\\\/]bin[\\\/]/;function $e(e){if(!e)return{kind:"empty"};const o=e.replace(/^\s*[>$#]\s+/,"").trim();return o?/[\r\n]/.test(o)?{kind:"multiline",value:o}:Fe.test(o)?{kind:"command",value:o}:Re.test(o)?{kind:"command",value:o}:_e.test(o)?{kind:"command",value:o}:o.length<3?{kind:"tooShort",value:o}:{kind:"ok",value:o}:{kind:"empty"}}async function De({yes:e}){if(e||!process.stdin.isTTY)return"";const{gray:o,yellow:n,cyan:t}=await import("../ui/output.mjs"),r=" "+o(`What should the next AI agent know about this project?
23
- > `),c=m=>new Promise(j=>{const p=H.createInterface({input:process.stdin,output:process.stdout});let h=!1;p.on("SIGINT",()=>{h=!0,p.close(),j(null)}),p.on("close",()=>{h&&j(null)}),p.question(m,S=>{p.close(),j(S)})});for(let m=0;m<2;m++){const j=await c(m===0?r:" "+o("> "));if(j===null)return console.log(),"";const p=$e(j);if(p.kind==="ok")return p.value;if(p.kind==="empty")return"";if(p.kind==="command"){console.log(" "+n("\u26A0")+" That looks like a shell command, not a memory."),console.log(" "+o(" Try a short note like: ")+t('"API returns 202 not 200 on async upload"'));continue}if(p.kind==="multiline"){console.log(" "+n("\u26A0")+" Multi-line paste detected \u2014 log a single gotcha at a time."),console.log(" "+o(" Try one short sentence:"));continue}if(p.kind==="tooShort"){console.log(" "+n("\u26A0")+" Too short to be useful as a memory. Skip with Enter, or try again:");continue}}return""}async function Ge(e,o,n){const{bold:t,cyan:r,gray:c,green:m,yellow:j}=await import("../ui/output.mjs"),p=s.join(e,".ai-memory"),h=s.join(e,"inferno"),S=s.join(p,"sessions.jsonl"),O=i.existsSync(S),E=i.existsSync(s.join(h,"sessions.jsonl"));if((O||E)&&!o){const w=i.existsSync(p)?".ai-memory/":"inferno/ (legacy)";console.log(`
24
- `+t("\u{1F525} infernoflow")+c(` \u2014 already set up
25
- `)),console.log(" "+m("\u2714")+" "+w+` found
26
- `),X(e),B(e);try{Z(e,{silent:!0})}catch{}console.log(" Quick commands:"),console.log(" "+r('infernoflow log "..."')+c(" \u2014 remember something")),console.log(" "+r("infernoflow switch")+c(" \u2014 handoff to next AI")),console.log(" "+r("infernoflow recap")+c(` \u2014 session summary
27
- `)),i.existsSync(p)||console.log(c(" Tip: run ")+r("infernoflow amp migrate")+c(` to move legacy memory into .ai-memory/
28
- `)),console.log(c(` For contracts & CI gates: infernoflow init --mode full
17
+ `;n.writeFileSync(e,t)}async function Re(e,o){const{bold:t,cyan:s,gray:r,green:l,yellow:d,red:y}=await import("../ui/output.mjs");console.log(`
18
+ `+t("\u{1F525} infernoflow init --lite")),console.log(" "+"\u2500".repeat(50)+`
19
+ `),console.log(r(" Lite mode: 3 files, no scripts, no workflows, no hooks.")),console.log(r(" Use `infernoflow upgrade` later to expand to the full setup.\n"));const a=i.join(e,"inferno");n.existsSync(a)&&!o&&(console.log(d(` \u26A0 inferno/ already exists. Use --force to overwrite.
20
+ `)),process.exit(0)),n.mkdirSync(a,{recursive:!0});const u=K(e);let S="";if(!process.argv.includes("--yes")&&!process.argv.includes("-y")&&process.stdin.isTTY){const E=H.createInterface({input:process.stdin,output:process.stdout});S=await new Promise(O=>{E.question(r(" What does this project do? (one line, Enter to skip): "),I=>{E.close(),O(I.trim())})})}const x={policyId:u,policyVersion:1,lite:!0,capabilities:[],intent:S||void 0};n.writeFileSync(i.join(a,"contract.json"),JSON.stringify(x,null,2)+`
21
+ `),n.writeFileSync(i.join(a,"capabilities.json"),JSON.stringify([],null,2)+`
22
+ `),n.writeFileSync(i.join(a,"sessions.jsonl"),"","utf8"),n.writeFileSync(i.join(a,".lite"),"1","utf8"),console.log(l(" \u2714 Created inferno/contract.json")),console.log(l(" \u2714 Created inferno/capabilities.json")),console.log(l(" \u2714 Created inferno/sessions.jsonl")),console.log(),console.log(" "+t("Ready. Start using it:")),console.log(" "+s("infernoflow log")+r(` "what you're building" --type note`)),console.log(" "+s("infernoflow context")+r(" \u2014 generate AI context to paste")),console.log(" "+s("infernoflow init --mode full")+r(" \u2014 expand to full setup when you need it")),console.log()}const _e=/^(?:node|npm|npx|yarn|pnpm|bun|git|cd|mkdir|rm|ls|cat|echo|type|dir|copy|del|move|python|python3|pip|go|cargo|java|gradle|mvn|docker|kubectl|curl|wget|ssh|scp|chmod|chown|sudo|brew|apt|yum)\b/i,$e=/\s(?:&&|\|\||>>|>|<<|<|\|)\s/,De=/(?:^|\s)[A-Za-z]:\\|\.\.[\\\/]|[\\\/]bin[\\\/]/;function Ge(e){if(!e)return{kind:"empty"};const o=e.replace(/^\s*[>$#]\s+/,"").trim();return o?/[\r\n]/.test(o)?{kind:"multiline",value:o}:_e.test(o)?{kind:"command",value:o}:$e.test(o)?{kind:"command",value:o}:De.test(o)?{kind:"command",value:o}:o.length<3?{kind:"tooShort",value:o}:{kind:"ok",value:o}:{kind:"empty"}}async function Le({yes:e}){if(e||!process.stdin.isTTY)return"";const{gray:o,yellow:t,cyan:s}=await import("../ui/output.mjs"),r=" "+o(`What should the next AI agent know about this project?
23
+ > `),l=d=>new Promise(y=>{const a=H.createInterface({input:process.stdin,output:process.stdout});let u=!1;a.on("SIGINT",()=>{u=!0,a.close(),y(null)}),a.on("close",()=>{u&&y(null)}),a.question(d,S=>{a.close(),y(S)})});for(let d=0;d<2;d++){const y=await l(d===0?r:" "+o("> "));if(y===null)return console.log(),"";const a=Ge(y);if(a.kind==="ok")return a.value;if(a.kind==="empty")return"";if(a.kind==="command"){console.log(" "+t("\u26A0")+" That looks like a shell command, not a memory."),console.log(" "+o(" Try a short note like: ")+s('"API returns 202 not 200 on async upload"'));continue}if(a.kind==="multiline"){console.log(" "+t("\u26A0")+" Multi-line paste detected \u2014 log a single gotcha at a time."),console.log(" "+o(" Try one short sentence:"));continue}if(a.kind==="tooShort"){console.log(" "+t("\u26A0")+" Too short to be useful as a memory. Skip with Enter, or try again:");continue}}return""}async function He(e,o,t){const{bold:s,cyan:r,gray:l,green:d,yellow:y}=await import("../ui/output.mjs"),a=i.join(e,".ai-memory"),u=i.join(e,"inferno"),S=i.join(a,"sessions.jsonl"),x=n.existsSync(S),E=n.existsSync(i.join(u,"sessions.jsonl"));if((x||E)&&!o){const k=n.existsSync(a)?".ai-memory/":"inferno/ (legacy)";console.log(`
24
+ `+s("\u{1F525} infernoflow")+l(` \u2014 already set up
25
+ `)),console.log(" "+d("\u2714")+" "+k+` found
26
+ `),B(e),Z(e);try{Q(e,{silent:!0})}catch{}ee(e,o),oe(e,o),console.log(" Quick commands:"),console.log(" "+r('infernoflow log "..."')+l(" \u2014 remember something")),console.log(" "+r("infernoflow switch")+l(" \u2014 handoff to next AI")),console.log(" "+r("infernoflow recap")+l(` \u2014 session summary
27
+ `)),n.existsSync(a)||console.log(l(" Tip: run ")+r("infernoflow amp migrate")+l(` to move legacy memory into .ai-memory/
28
+ `)),console.log(l(` For contracts & CI gates: infernoflow init --mode full
29
29
  `));return}const I=K(e);console.log(`
30
- `+t("\u{1F525} infernoflow")+c(` \u2014 let's get you set up (30 seconds)
30
+ `+s("\u{1F525} infernoflow")+l(` \u2014 let's get you set up (30 seconds)
31
31
  `)),console.log(" Detected: "+r(I)+`
32
- `),Se(e),i.existsSync(S)||i.writeFileSync(S,"","utf8"),ve(e,{project:I,config:{autoCapture:!0}}),X(e);const F=B(e);for(const w of F)"created"in w&&(w.created||w.updated)&&g((w.created?"Created: ":"Updated: ")+r(w.rel));try{Z(e)}catch(w){T("MCP auto-setup skipped: "+w.message)}const P=await De({yes:n});P?(V(e,{ts:new Date().toISOString(),agent:"user",type:"gotcha",summary:P,source:"init"}),console.log(`
33
- `+m("\u2714")+" First gotcha logged!")):n&&V(e,{ts:new Date().toISOString(),agent:"infernoflow",type:"note",summary:"infernoflow init complete \u2014 memory loop is live. Run `infernoflow status` to verify.",source:"init"}),console.log(`
34
- `+m("\u2714")+` You're set up. Quick commands:
35
- `),console.log(" "+r("infernoflow status")+c(" \u2014 verify the loop end-to-end")),console.log(" "+r('infernoflow log "..."')+c(" \u2014 remember something")),console.log(" "+r("infernoflow switch")+c(" \u2014 generate handoff for next AI")),console.log(" "+r("infernoflow recap")+c(` \u2014 session summary
36
- `)),console.log(c(` Tip: infernoflow switch --copy puts the handoff on your clipboard.
37
- `))}function Le(){console.log(["infernoflow init \u2014 set up persistent AI memory in this project","","Usage:"," infernoflow init Memory-first setup (default, 60 sec)"," infernoflow init --lite Minimal: 3 files, no scripts, no workflows"," infernoflow init --mode full Contracts + CI gates (advanced)"," infernoflow init --adopt Detect existing capabilities from code"," infernoflow init --template <name> Start from a project template","","Options:"," -y, --yes Non-interactive; accept all defaults"," -f, --force Overwrite existing inferno/ or .ai-memory/"," --cursor-hooks Also install Cursor IDE hooks (advanced)"," --vscode-copilot-hooks Also install VS Code Copilot hooks (advanced)"," --lang <lang> Override language detection (with --adopt)"," --framework <name> Override framework detection (with --adopt)"," --project-type <type> Override project-type detection (with --adopt)"," -h, --help Show this help","","Default flow writes .ai-memory/ + AI rule files + MCP server config, then asks","for one first gotcha. Press Enter to skip \u2014 never blocks."].join(`
38
- `))}async function eo(e){if(e.includes("--help")||e.includes("-h")){Le();return}const o=process.cwd(),n=e.includes("--force")||e.includes("-f"),t=e.includes("--yes")||e.includes("-y"),r=e.includes("--adopt"),c=e.find(a=>a.startsWith("--mode="))?.split("=")[1]||(e.indexOf("--mode")!==-1?e[e.indexOf("--mode")+1]:null),m=c==="full"||c==="contract",j=r||e.includes("--template")||e.includes("--cursor-hooks")||e.includes("--vscode-copilot-hooks")||e.includes("--lite");if(!m&&!j){await Ge(o,n,t);return}if(e.includes("--lite")){await Ne(o,n);return}const p=e.indexOf("--template"),h=p!==-1?e[p+1]:null;if(h){let a;try{a=await import("../templates/index.mjs")}catch{}const l=a?.getTemplate(h);if(!l){const d=a?a.listTemplates().map(A=>A.name).join(", "):"rest-api, nextjs, cli, graphql, monorepo";T(`Unknown template: ${h}. Available: ${d}`),process.exit(1)}const y=s.join(o,"inferno"),N=s.join(y,"scenarios");i.existsSync(y)||i.mkdirSync(y,{recursive:!0}),i.existsSync(N)||i.mkdirSync(N,{recursive:!0});const D=K(o),k=l.capabilities;i.writeFileSync(s.join(y,"contract.json"),JSON.stringify({policyId:D,policyVersion:1,capabilities:k.map(d=>d.id)},null,2)+`
39
- `),i.writeFileSync(s.join(y,"capabilities.json"),JSON.stringify({capabilities:k.map(d=>({id:d.id,description:d.description,since:new Date().toISOString().slice(0,10),source:`template:${h}`}))},null,2)+`
40
- `);for(const d of k)i.writeFileSync(s.join(N,`${d.id}.json`),JSON.stringify({id:`${d.id}-happy-path`,capability:d.id,description:`Happy path for ${d.description||d.id}`,steps:[{action:"invoke",target:d.id,input:{}},{action:"assert",field:"status",value:"success"}],capabilitiesCovered:[d.id]},null,2)+`
41
- `);oe(s.join(y,"CHANGELOG.md"),D),i.writeFileSync(s.join(y,"CONTEXT.md"),`# ${D} \u2014 infernoflow context
32
+ `),Ce(e),n.existsSync(S)||n.writeFileSync(S,"","utf8"),xe(e,{project:I,config:{autoCapture:!0}}),B(e);const N=Z(e);for(const k of N)"created"in k&&(k.created||k.updated)&&w((k.created?"Created: ":"Updated: ")+r(k.rel));ee(e,o),oe(e,o);try{Q(e)}catch(k){T("MCP auto-setup skipped: "+k.message)}const P=await Le({yes:t});P?(X(e,{ts:new Date().toISOString(),agent:"user",type:"gotcha",summary:P,source:"init"}),console.log(`
33
+ `+d("\u2714")+" First gotcha logged!")):t&&X(e,{ts:new Date().toISOString(),agent:"infernoflow",type:"note",summary:"infernoflow init complete \u2014 memory loop is live. Run `infernoflow status` to verify.",source:"init"}),console.log(`
34
+ `+d("\u2714")+` You're set up. Quick commands:
35
+ `),console.log(" "+r("infernoflow status")+l(" \u2014 verify the loop end-to-end")),console.log(" "+r('infernoflow log "..."')+l(" \u2014 remember something")),console.log(" "+r("infernoflow switch")+l(" \u2014 generate handoff for next AI")),console.log(" "+r("infernoflow recap")+l(` \u2014 session summary
36
+ `)),console.log(l(` Tip: infernoflow switch --copy puts the handoff on your clipboard.
37
+ `))}function Je(){console.log(["infernoflow init \u2014 set up persistent AI memory in this project","","Usage:"," infernoflow init Memory-first setup (default, 60 sec)"," infernoflow init --lite Minimal: 3 files, no scripts, no workflows"," infernoflow init --mode full Contracts + CI gates (advanced)"," infernoflow init --adopt Detect existing capabilities from code"," infernoflow init --template <name> Start from a project template","","Options:"," -y, --yes Non-interactive; accept all defaults"," -f, --force Overwrite existing inferno/ or .ai-memory/"," --cursor-hooks Also install Cursor IDE hooks (advanced)"," --vscode-copilot-hooks Also install VS Code Copilot hooks (advanced)"," --lang <lang> Override language detection (with --adopt)"," --framework <name> Override framework detection (with --adopt)"," --project-type <type> Override project-type detection (with --adopt)"," -h, --help Show this help","","Default flow writes .ai-memory/ + AI rule files + MCP server config, then asks","for one first gotcha. Press Enter to skip \u2014 never blocks."].join(`
38
+ `))}async function no(e){if(e.includes("--help")||e.includes("-h")){Je();return}const o=process.cwd(),t=e.includes("--force")||e.includes("-f"),s=e.includes("--yes")||e.includes("-y"),r=e.includes("--adopt"),l=e.find(p=>p.startsWith("--mode="))?.split("=")[1]||(e.indexOf("--mode")!==-1?e[e.indexOf("--mode")+1]:null),d=l==="full"||l==="contract",y=r||e.includes("--template")||e.includes("--cursor-hooks")||e.includes("--vscode-copilot-hooks")||e.includes("--lite");if(!d&&!y){await He(o,t,s);return}if(e.includes("--lite")){await Re(o,t);return}const a=e.indexOf("--template"),u=a!==-1?e[a+1]:null;if(u){let p;try{p=await import("../templates/index.mjs")}catch{}const c=p?.getTemplate(u);if(!c){const m=p?p.listTemplates().map(A=>A.name).join(", "):"rest-api, nextjs, cli, graphql, monorepo";T(`Unknown template: ${u}. Available: ${m}`),process.exit(1)}const h=i.join(o,"inferno"),F=i.join(h,"scenarios");n.existsSync(h)||n.mkdirSync(h,{recursive:!0}),n.existsSync(F)||n.mkdirSync(F,{recursive:!0});const D=K(o),j=c.capabilities;n.writeFileSync(i.join(h,"contract.json"),JSON.stringify({policyId:D,policyVersion:1,capabilities:j.map(m=>m.id)},null,2)+`
39
+ `),n.writeFileSync(i.join(h,"capabilities.json"),JSON.stringify({capabilities:j.map(m=>({id:m.id,description:m.description,since:new Date().toISOString().slice(0,10),source:`template:${u}`}))},null,2)+`
40
+ `);for(const m of j)n.writeFileSync(i.join(F,`${m.id}.json`),JSON.stringify({id:`${m.id}-happy-path`,capability:m.id,description:`Happy path for ${m.description||m.id}`,steps:[{action:"invoke",target:m.id,input:{}},{action:"assert",field:"status",value:"success"}],capabilitiesCovered:[m.id]},null,2)+`
41
+ `);ie(i.join(h,"CHANGELOG.md"),D),n.writeFileSync(i.join(h,"CONTEXT.md"),`# ${D} \u2014 infernoflow context
42
42
 
43
- > Template: ${h} \u2014 ${l.description}
43
+ > Template: ${u} \u2014 ${c.description}
44
44
 
45
45
  ## Hint
46
- ${l.contextHint}
46
+ ${c.contextHint}
47
47
 
48
- ## Capabilities (${k.length})
49
- ${k.map(d=>`- \`${d.id}\`: ${d.description}`).join(`
48
+ ## Capabilities (${j.length})
49
+ ${j.map(m=>`- \`${m.id}\`: ${m.description}`).join(`
50
50
  `)}
51
- `),l.scripts&&(q("Suggested package.json scripts for this template:"),Object.entries(l.scripts).forEach(([d,A])=>console.log(` ${J(d)}: ${v(A)}`)),console.log()),z(`Initialised from template ${J(f(h))} \u2014 ${J(String(k.length))} capabilities`),console.log(),q(`Run ${f("infernoflow vibe")} to start vibe coding mode`),console.log();return}const S=e.includes("--cursor-hooks"),O=e.includes("--vscode-copilot-hooks"),E=e.includes("--report-json"),x=e.includes("--report-json-only"),I=e.includes("--report-human-only"),F=W(e,"--lang"),P=W(e,"--framework"),w=W(e,"--project-type"),u=x;x&&I&&(console.error("Error: --report-json-only and --report-human-only cannot be used together."),process.exit(1)),u||ue("init");const b=s.join(o,"inferno"),ne=s.join(o,".github","workflows");i.existsSync(b)&&!n&&(u&&(console.log(JSON.stringify({ok:!1,error:"inferno_exists",hint:"Use --force to overwrite"},null,2)),process.exit(1)),T("inferno/ already exists. Use --force to overwrite."),console.log(),process.exit(0));const R=K(o),Y="CreateTask, ReadTasks, UpdateTask, ToggleComplete, DeleteTask";let _=R,C=Y.split(",").map(a=>a.trim());if(r||m){let l=M(o,{language:F||void 0,framework:P||void 0,projectType:w||void 0});if(!t&&!x){const k=H.createInterface({input:process.stdin,output:process.stdout}),d=l.developmentProfile||{},A=d.detected||{};console.log(v(` Review inferred development stack (press Enter to accept detected values)
52
- `));const ae=await L(k,"Language",d.language||A.language||"unknown"),pe=await L(k,"Framework",d.framework||A.framework||"unknown"),fe=await L(k,"Project type",d.projectType||A.projectType||"unknown");k.close(),l=M(o,{language:ae,framework:pe,projectType:fe})}const y=l.capabilities,N=we(y);x?console.log(JSON.stringify({mode:"adopt",policyId:R,inferredCapabilities:N,components:l.components,displayFields:l.displayFields,externalLibraries:l.externalLibraries,uiLayout:l.uiLayout,styling:l.styling,developmentProfile:l.developmentProfile,apiCalls:l.apiCalls},null,2)):(console.log(),console.log(v(he(y))),console.log(),console.log(v(ke(l))),console.log(),E&&!I&&(console.log(JSON.stringify({mode:"adopt",policyId:R,inferredCapabilities:N,components:l.components,displayFields:l.displayFields,externalLibraries:l.externalLibraries,uiLayout:l.uiLayout,styling:l.styling,developmentProfile:l.developmentProfile,apiCalls:l.apiCalls},null,2)),console.log()));const D=await ye(y,t);_=R,C=D.map(k=>k.id),C.length===0&&(C=["ExampleCapability"],u||T("No capabilities detected from the code \u2014 wrote a placeholder. Edit "+f("inferno/capabilities.json")+" to describe what this project does."))}else if(!t){const a=H.createInterface({input:process.stdin,output:process.stdout});console.log(v(` Press Enter to accept defaults
53
- `)),_=await L(a,"Project / policy name",R),C=(await L(a,"Capabilities (comma-separated)",Y)).split(",").map(y=>y.trim()).filter(Boolean),a.close(),console.log()}if(i.mkdirSync(b,{recursive:!0}),r){const a=C.map(y=>({id:y,title:y.replace(/([A-Z])/g," $1").trim()})),l=M(o,{language:F||void 0,framework:P||void 0,projectType:w||void 0});ge(b,_,a,l),u||(g("Created: "+f("inferno/contract.json")),g("Created: "+f("inferno/capabilities.json")),g("Created: "+f("inferno/scenarios/adoption_baseline.json")),g("Created: "+f("inferno/adoption_profile.json")),g("Created: "+f("inferno/CHANGELOG.md")))}else Te(s.join(b,"contract.json"),_,C),u||g("Created: "+f("inferno/contract.json")),Ee(s.join(b,"capabilities.json"),C),u||g("Created: "+f("inferno/capabilities.json")),Pe(s.join(b,"scenarios"),C),u||g("Created: "+f("inferno/scenarios/happy_path.json")),oe(s.join(b,"CHANGELOG.md"),_),u||g("Created: "+f("inferno/CHANGELOG.md"));const $=Oe(),te=s.join($,"scripts","inferno-doc-gate.mjs"),ie=s.join(o,"scripts","inferno-doc-gate.mjs");U(te,ie,n,u);const se=s.join($,"scripts","inferno-install-hooks.mjs"),re=s.join(o,"scripts","inferno-install-hooks.mjs");U(se,re,n,u);const le=s.join($,"ci","github-inferno-check.yml"),ce=s.join(ne,"infernoflow-check.yml");if(U(le,ce,n,u),Ie(o,u),S&&je({cwd:o,templatesRoot:$,force:n,silent:u,logOk:a=>{u||g(a)},logWarn:a=>{u||T(a)}}),O&&be({cwd:o,templatesRoot:$,force:n,silent:u,logOk:a=>{u||g(a)},logWarn:a=>{u||T(a)}}),r){const a=s.join(b,"context-state.json");let l={};try{l=JSON.parse(i.readFileSync(a,"utf8"))}catch{}const y=M(o,{language:F||void 0,framework:P||void 0,projectType:w||void 0});l.stack=y.developmentProfile,i.writeFileSync(a,JSON.stringify(l,null,2)+`
54
- `,"utf8"),u||g("Created: "+f("inferno/context-state.json"))}if(!u){z("infernoflow initialized!");const a=s.join(b,"integrations.json");!(process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GOOGLE_AI_API_KEY||process.env.OPENROUTER_API_KEY||process.env.GEMINI_API_KEY)&&!i.existsSync(a)&&(console.log(),console.log(` ${G("\u{1F4A1}")} ${J("Tip:")} connect an AI provider for explain, why, review, and changelog AI.`),console.log(` ${f("infernoflow ai setup")} \u2014 takes 60 seconds`)),me([f("infernoflow status")+" \u2014 see your contract at a glance",f("infernoflow check")+" \u2014 validate everything",(r?"Review inferred baseline in ":"Edit ")+G("inferno/capabilities.json")+(r?" and refine IDs/titles":" to describe each capability in detail"),"Add more "+G("inferno/scenarios/*.json")+" files for edge cases","Add "+f("inferno:check")+" to your CI pipeline",...S?["Restart Cursor \u2014 hooks write assistant text to "+G("inferno/CONTEXT.draft.md"),"Promote when ready: "+f("npm run inferno:promote-draft -- --append-notes")]:[],...O?["Restart VS Code \u2014 Copilot hooks append prompts + assistant (from transcript) to "+G("inferno/CONTEXT.draft.md"),"Promote when ready: "+f("npm run inferno:promote-draft -- --append-notes")]:[],...!S&&!O?["Optional: "+f("infernoflow install-cursor-hooks")+" or "+f("infernoflow install-vscode-copilot-hooks")]:[]])}}export{Qe as ensureGitignoreEntries,eo as initCommand};
51
+ `),c.scripts&&(z("Suggested package.json scripts for this template:"),Object.entries(c.scripts).forEach(([m,A])=>console.log(` ${J(m)}: ${v(A)}`)),console.log()),V(`Initialised from template ${J(f(u))} \u2014 ${J(String(j.length))} capabilities`),console.log(),z(`Run ${f("infernoflow vibe")} to start vibe coding mode`),console.log();return}const S=e.includes("--cursor-hooks"),x=e.includes("--vscode-copilot-hooks"),E=e.includes("--report-json"),O=e.includes("--report-json-only"),I=e.includes("--report-human-only"),N=Y(e,"--lang"),P=Y(e,"--framework"),k=Y(e,"--project-type"),g=O;O&&I&&(console.error("Error: --report-json-only and --report-human-only cannot be used together."),process.exit(1)),g||ge("init");const b=i.join(o,"inferno"),se=i.join(o,".github","workflows");n.existsSync(b)&&!t&&(g&&(console.log(JSON.stringify({ok:!1,error:"inferno_exists",hint:"Use --force to overwrite"},null,2)),process.exit(1)),T("inferno/ already exists. Use --force to overwrite."),console.log(),process.exit(0));const R=K(o),q="CreateTask, ReadTasks, UpdateTask, ToggleComplete, DeleteTask";let _=R,C=q.split(",").map(p=>p.trim());if(r||d){let c=M(o,{language:N||void 0,framework:P||void 0,projectType:k||void 0});if(!s&&!O){const j=H.createInterface({input:process.stdin,output:process.stdout}),m=c.developmentProfile||{},A=m.detected||{};console.log(v(` Review inferred development stack (press Enter to accept detected values)
52
+ `));const de=await L(j,"Language",m.language||A.language||"unknown"),ue=await L(j,"Framework",m.framework||A.framework||"unknown"),me=await L(j,"Project type",m.projectType||A.projectType||"unknown");j.close(),c=M(o,{language:de,framework:ue,projectType:me})}const h=c.capabilities,F=Se(h);O?console.log(JSON.stringify({mode:"adopt",policyId:R,inferredCapabilities:F,components:c.components,displayFields:c.displayFields,externalLibraries:c.externalLibraries,uiLayout:c.uiLayout,styling:c.styling,developmentProfile:c.developmentProfile,apiCalls:c.apiCalls},null,2)):(console.log(),console.log(v(je(h))),console.log(),console.log(v(ve(c))),console.log(),E&&!I&&(console.log(JSON.stringify({mode:"adopt",policyId:R,inferredCapabilities:F,components:c.components,displayFields:c.displayFields,externalLibraries:c.externalLibraries,uiLayout:c.uiLayout,styling:c.styling,developmentProfile:c.developmentProfile,apiCalls:c.apiCalls},null,2)),console.log()));const D=await we(h,s);_=R,C=D.map(j=>j.id),C.length===0&&(C=["ExampleCapability"],g||T("No capabilities detected from the code \u2014 wrote a placeholder. Edit "+f("inferno/capabilities.json")+" to describe what this project does."))}else if(!s){const p=H.createInterface({input:process.stdin,output:process.stdout});console.log(v(` Press Enter to accept defaults
53
+ `)),_=await L(p,"Project / policy name",R),C=(await L(p,"Capabilities (comma-separated)",q)).split(",").map(h=>h.trim()).filter(Boolean),p.close(),console.log()}if(n.mkdirSync(b,{recursive:!0}),r){const p=C.map(h=>({id:h,title:h.replace(/([A-Z])/g," $1").trim()})),c=M(o,{language:N||void 0,framework:P||void 0,projectType:k||void 0});ke(b,_,p,c),g||(w("Created: "+f("inferno/contract.json")),w("Created: "+f("inferno/capabilities.json")),w("Created: "+f("inferno/scenarios/adoption_baseline.json")),w("Created: "+f("inferno/adoption_profile.json")),w("Created: "+f("inferno/CHANGELOG.md")))}else Pe(i.join(b,"contract.json"),_,C),g||w("Created: "+f("inferno/contract.json")),Fe(i.join(b,"capabilities.json"),C),g||w("Created: "+f("inferno/capabilities.json")),Ne(i.join(b,"scenarios"),C),g||w("Created: "+f("inferno/scenarios/happy_path.json")),ie(i.join(b,"CHANGELOG.md"),_),g||w("Created: "+f("inferno/CHANGELOG.md"));const $=W(),re=i.join($,"scripts","inferno-doc-gate.mjs"),le=i.join(o,"scripts","inferno-doc-gate.mjs");U(re,le,t,g);const ce=i.join($,"scripts","inferno-install-hooks.mjs"),ae=i.join(o,"scripts","inferno-install-hooks.mjs");U(ce,ae,t,g);const pe=i.join($,"ci","github-inferno-check.yml"),fe=i.join(se,"infernoflow-check.yml");if(U(pe,fe,t,g),Te(o,g),S&&be({cwd:o,templatesRoot:$,force:t,silent:g,logOk:p=>{g||w(p)},logWarn:p=>{g||T(p)}}),x&&Oe({cwd:o,templatesRoot:$,force:t,silent:g,logOk:p=>{g||w(p)},logWarn:p=>{g||T(p)}}),r){const p=i.join(b,"context-state.json");let c={};try{c=JSON.parse(n.readFileSync(p,"utf8"))}catch{}const h=M(o,{language:N||void 0,framework:P||void 0,projectType:k||void 0});c.stack=h.developmentProfile,n.writeFileSync(p,JSON.stringify(c,null,2)+`
54
+ `,"utf8"),g||w("Created: "+f("inferno/context-state.json"))}if(!g){V("infernoflow initialized!");const p=i.join(b,"integrations.json");!(process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GOOGLE_AI_API_KEY||process.env.OPENROUTER_API_KEY||process.env.GEMINI_API_KEY)&&!n.existsSync(p)&&(console.log(),console.log(` ${G("\u{1F4A1}")} ${J("Tip:")} connect an AI provider for explain, why, review, and changelog AI.`),console.log(` ${f("infernoflow ai setup")} \u2014 takes 60 seconds`)),he([f("infernoflow status")+" \u2014 see your contract at a glance",f("infernoflow check")+" \u2014 validate everything",(r?"Review inferred baseline in ":"Edit ")+G("inferno/capabilities.json")+(r?" and refine IDs/titles":" to describe each capability in detail"),"Add more "+G("inferno/scenarios/*.json")+" files for edge cases","Add "+f("inferno:check")+" to your CI pipeline",...S?["Restart Cursor \u2014 hooks write assistant text to "+G("inferno/CONTEXT.draft.md"),"Promote when ready: "+f("npm run inferno:promote-draft -- --append-notes")]:[],...x?["Restart VS Code \u2014 Copilot hooks append prompts + assistant (from transcript) to "+G("inferno/CONTEXT.draft.md"),"Promote when ready: "+f("npm run inferno:promote-draft -- --append-notes")]:[],...!S&&!x?["Optional: "+f("infernoflow install-cursor-hooks")+" or "+f("infernoflow install-vscode-copilot-hooks")]:[]])}}export{oo as ensureGitignoreEntries,no as initCommand};
@@ -1,14 +1,14 @@
1
- import*as u from"node:fs";import*as y from"node:path";import{execSync as j}from"node:child_process";import{readEntries as v,readConfig as x}from"./amp/io.mjs";const g="<!-- infernoflow:start -->",m="<!-- infernoflow:end -->",w=[".cursorrules","CLAUDE.md",y.join(".github","copilot-instructions.md")],k=4,C=5,S=200;function A(e){const o=e&&e.config||{},t=o.injection&&typeof o.injection=="object"?o.injection:{},n=Array.isArray(o.inject)&&!o.inject.includes("all")?o.inject:null,r=["full","compact","off"].includes(t.protocolStyle)?t.protocolStyle:"compact",s=t.includeProtocol===!1?"off":r;return{maxEntries:Number.isInteger(t.maxEntries)&&t.maxEntries>=0?t.maxEntries:k,maxCommits:Number.isInteger(t.maxCommits)&&t.maxCommits>=0?t.maxCommits:C,maxEntryChars:Number.isInteger(t.maxEntryChars)&&t.maxEntryChars>0?t.maxEntryChars:S,targets:Array.isArray(t.targets)&&t.targets.length?t.targets:n||w,protocolStyle:s,includeProtocol:s!=="off"}}function T(e){if(!u.existsSync(e))return{stripped:!1};const o=u.readFileSync(e,"utf8"),t=o.indexOf(g),n=o.indexOf(m);if(t===-1||n===-1||n<=t)return{stripped:!1};const r=o.slice(0,t).replace(/\s+$/,""),s=o.slice(n+m.length).replace(/^\s+/,""),i=r&&s?r+`
1
+ import*as u from"node:fs";import*as y from"node:path";import{execSync as j}from"node:child_process";import{readEntries as v,readConfig as x}from"./amp/io.mjs";import{ensureClaudeAssets as T}from"./claudeAssets.mjs";const g="<!-- infernoflow:start -->",m="<!-- infernoflow:end -->",w=[".cursorrules","CLAUDE.md",y.join(".github","copilot-instructions.md")],k=4,C=5,S=200;function A(e){const o=e&&e.config||{},t=o.injection&&typeof o.injection=="object"?o.injection:{},n=Array.isArray(o.inject)&&!o.inject.includes("all")?o.inject:null,r=["full","compact","off"].includes(t.protocolStyle)?t.protocolStyle:"compact",s=t.includeProtocol===!1?"off":r;return{maxEntries:Number.isInteger(t.maxEntries)&&t.maxEntries>=0?t.maxEntries:k,maxCommits:Number.isInteger(t.maxCommits)&&t.maxCommits>=0?t.maxCommits:C,maxEntryChars:Number.isInteger(t.maxEntryChars)&&t.maxEntryChars>0?t.maxEntryChars:S,targets:Array.isArray(t.targets)&&t.targets.length?t.targets:n||w,protocolStyle:s,includeProtocol:s!=="off"}}function F(e){if(!u.existsSync(e))return{stripped:!1};const o=u.readFileSync(e,"utf8"),t=o.indexOf(g),n=o.indexOf(m);if(t===-1||n===-1||n<=t)return{stripped:!1};const r=o.slice(0,t).replace(/\s+$/,""),s=o.slice(n+m.length).replace(/^\s+/,""),i=r&&s?r+`
2
2
 
3
3
  `+s:r||s;return u.writeFileSync(e,i?i.replace(/\s*$/,"")+`
4
- `:"","utf8"),{stripped:!0}}function E(e="compact"){return e==="off"?"":e==="full"?M():F()}function F(){return["### Memory protocol","",'Use the `amp_write` and `amp_bookmark` MCP tools **proactively** (without being asked): log a one-sentence entry when the user hits frustration (`!!` / "not working" / "retry" \u2192 `attempt`), a `decision` is made, or you learn a non-obvious `gotcha`; drop a bookmark on "bookmark this". Don\'t log what\'s re-derivable from the code. The full trigger list and field shapes are in the tool descriptions \u2014 if the `amp_*` tools aren\'t visible, load them first (Claude Code: `ToolSearch` with query `infernoflow`).'].join(`
5
- `)}function M(){const e=[];return e.push("### Memory protocol \u2014 capture as you go"),e.push(""),e.push("You have the `amp_write` MCP tool. **Use it proactively** (without the user asking) whenever you detect any of these moments. Capture the lesson in one sentence so the next AI session inherits it."),e.push(""),e.push("**If `amp_write` is not in your visible tools**, your client uses deferred MCP loading \u2014 call your tool-discovery mechanism (Claude Code: `ToolSearch` with query `infernoflow`) to load the `amp_*` tools BEFORE proceeding. Don't silently skip the protocol because the tool isn't visible yet."),e.push(""),e.push("| When you see\u2026 | Call `amp_write` with\u2026 |"),e.push("|---|---|"),e.push("| User types `!!`, `!!!`, `not working`, `still broken`, `no change`, `same error`, `retry` / `retrying`, repeated frustration | `{type: 'attempt', msg: '<one-line: what was tried and how it failed>', file: '<active file>'}` |"),e.push("| You generate a plan, numbered steps, or `Plan:` / `Approach:` block | `{type: 'note', msg: 'Plan: <one-line summary>', file: '<focus file>'}` |"),e.push("| User picks X over Y, decides an architectural approach, or you both agree on a direction | `{type: 'decision', msg: '<X> chosen over <Y> because <reason>', file: '<file>'}` |"),e.push("| Discovered non-obvious behavior, API quirk, or `aha \u2014 turns out\u2026` moment | `{type: 'gotcha', msg: '<one-line>', file: '<file>', line: <line if known>}` |"),e.push("| User says `switching` / `back to X`, or ~30 min passed without logging | `{type: 'note', msg: 'Session snapshot \u2014 worked on: <X>. Open threads: <Y>.'}` |"),e.push(""),e.push("**Do NOT log:** typos, syntax errors, obvious bugs visible in the code, anything the next AI can infer by re-reading the file."),e.push("**Do log:** anything that taught you something non-derivable from code."),e.push("**Be concise:** entries should be one sentence. Future-you will skim them."),e.push("**Bookmark resume points:** when the user says `bookmark this` / `mark this point`, or the context window is filling up while work is mid-flight, call `amp_bookmark` with a short `label` (omit `note` to auto-capture the session transcript) \u2014 so they can jump back to that exact point in the next session."),e.push("**When you use a \u{1F525} memory entry in your reply, briefly cite it** \u2014 e.g. `\u{1F525} (from infernoflow memory) gotcha at src/api.js:42: ...` \u2014 so the user can see which guidance came from project memory vs. your own inference."),e.join(`
6
- `)}function D(e="compact"){const o=E(e);return[g,"<!-- Auto-managed by infernoflow. Don't edit between these markers. -->","## Project memory (infernoflow)","",...o?[o,""]:[],'_No entries yet. They\'ll appear here as you and your AI tools log them \u2014 run `infernoflow log "..."` or call `amp_write` from any MCP-aware AI._',m].join(`
7
- `)}function R(e){const o=e.indexOf("<!-- AMP:START -->"),t=e.indexOf("<!-- AMP:END -->");if(o===-1||t===-1||t<=o)return e;const n=e.slice(0,o).replace(/\s+$/,""),r=e.slice(t+16).replace(/^\s+/,"");return(n?n+(r?`
4
+ `:"","utf8"),{stripped:!0}}function E(e="compact"){return e==="off"?"":e==="full"?D():M()}function M(){return["### Memory protocol","",'Use the `amp_write` and `amp_bookmark` MCP tools **proactively** (without being asked): log a one-sentence entry when the user hits frustration (`!!` / "not working" / "retry" \u2192 `attempt`), a `decision` is made, or you learn a non-obvious `gotcha`; drop a bookmark on "bookmark this". Don\'t log what\'s re-derivable from the code. The full trigger list and field shapes are in the tool descriptions \u2014 if the `amp_*` tools aren\'t visible, load them first (Claude Code: `ToolSearch` with query `infernoflow`).'].join(`
5
+ `)}function D(){const e=[];return e.push("### Memory protocol \u2014 capture as you go"),e.push(""),e.push("You have the `amp_write` MCP tool. **Use it proactively** (without the user asking) whenever you detect any of these moments. Capture the lesson in one sentence so the next AI session inherits it."),e.push(""),e.push("**If `amp_write` is not in your visible tools**, your client uses deferred MCP loading \u2014 call your tool-discovery mechanism (Claude Code: `ToolSearch` with query `infernoflow`) to load the `amp_*` tools BEFORE proceeding. Don't silently skip the protocol because the tool isn't visible yet."),e.push(""),e.push("| When you see\u2026 | Call `amp_write` with\u2026 |"),e.push("|---|---|"),e.push("| User types `!!`, `!!!`, `not working`, `still broken`, `no change`, `same error`, `retry` / `retrying`, repeated frustration | `{type: 'attempt', msg: '<one-line: what was tried and how it failed>', file: '<active file>'}` |"),e.push("| You generate a plan, numbered steps, or `Plan:` / `Approach:` block | `{type: 'note', msg: 'Plan: <one-line summary>', file: '<focus file>'}` |"),e.push("| User picks X over Y, decides an architectural approach, or you both agree on a direction | `{type: 'decision', msg: '<X> chosen over <Y> because <reason>', file: '<file>'}` |"),e.push("| Discovered non-obvious behavior, API quirk, or `aha \u2014 turns out\u2026` moment | `{type: 'gotcha', msg: '<one-line>', file: '<file>', line: <line if known>}` |"),e.push("| User says `switching` / `back to X`, or ~30 min passed without logging | `{type: 'note', msg: 'Session snapshot \u2014 worked on: <X>. Open threads: <Y>.'}` |"),e.push(""),e.push("**Do NOT log:** typos, syntax errors, obvious bugs visible in the code, anything the next AI can infer by re-reading the file."),e.push("**Do log:** anything that taught you something non-derivable from code."),e.push("**Be concise:** entries should be one sentence. Future-you will skim them."),e.push("**Bookmark resume points:** when the user says `bookmark this` / `mark this point`, or the context window is filling up while work is mid-flight, call `amp_bookmark` with a short `label` (omit `note` to auto-capture the session transcript) \u2014 so they can jump back to that exact point in the next session."),e.push("**When you use a \u{1F525} memory entry in your reply, briefly cite it** \u2014 e.g. `\u{1F525} (from infernoflow memory) gotcha at src/api.js:42: ...` \u2014 so the user can see which guidance came from project memory vs. your own inference."),e.join(`
6
+ `)}function R(e="compact"){const o=E(e);return[g,"<!-- Auto-managed by infernoflow. Don't edit between these markers. -->","## Project memory (infernoflow)","",...o?[o,""]:[],'_No entries yet. They\'ll appear here as you and your AI tools log them \u2014 run `infernoflow log "..."` or call `amp_write` from any MCP-aware AI._',m].join(`
7
+ `)}function N(e){const o=e.indexOf("<!-- AMP:START -->"),t=e.indexOf("<!-- AMP:END -->");if(o===-1||t===-1||t<=o)return e;const n=e.slice(0,o).replace(/\s+$/,""),r=e.slice(t+16).replace(/^\s+/,"");return(n?n+(r?`
8
8
 
9
9
  `:""):"")+r}function I(e,o){const t=y.dirname(e);if(u.existsSync(t)||u.mkdirSync(t,{recursive:!0}),!u.existsSync(e))return u.writeFileSync(e,o+`
10
- `,"utf8"),{created:!0,updated:!1};let n=u.readFileSync(e,"utf8");n=R(n);const r=n.indexOf(g),s=n.indexOf(m);if(r===-1||s===-1){const d=o+`
10
+ `,"utf8"),{created:!0,updated:!1};let n=u.readFileSync(e,"utf8");n=N(n);const r=n.indexOf(g),s=n.indexOf(m);if(r===-1||s===-1){const d=o+`
11
11
 
12
- `+n;return u.writeFileSync(e,d,"utf8"),{created:!1,updated:!0}}const i=n.slice(0,r),p=n.slice(s+m.length),l=i+o+p;return l===n?{created:!1,updated:!1}:(u.writeFileSync(e,l,"utf8"),{created:!1,updated:!0})}function B(e){const{protocolStyle:o}=A(x(e)),t=D(o),n=[];for(const r of w){const s=y.join(e,r);try{const i=I(s,t);n.push({rel:r,...i})}catch(i){n.push({rel:r,error:i.message})}}return n}function N(e){return v(e)}function P(e,o=10){try{return j(`git log --pretty=format:"%h%x09%ad%x09%s" --date=short -n ${o}`,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
13
- `).filter(Boolean).map(n=>{const[r,s,i]=n.split(" ");return{hash:(r||"").slice(0,7),date:s||"",subject:i||""}})}catch{return[]}}function O(e,o={}){const{maxEntries:t=k,maxCommits:n=C,maxEntryChars:r=S,protocolStyle:s="compact",includeProtocol:i=!0}=o,p=N(e),l=P(e,n);p.sort((a,h)=>{const f=typeof a.ts=="number"?a.ts:Date.parse(a.ts||0);return(typeof h.ts=="number"?h.ts:Date.parse(h.ts||0))-f});const d=p.slice(0,t),_={gotcha:"\u26A0",decision:"\u2713",attempt:"\u2717",note:"\xB7",detection:"\u25CB",pattern:"\u25C7"},c=[];if(c.push(g),c.push("<!-- Auto-managed by infernoflow. Don't edit between these markers. -->"),c.push("## Project memory (infernoflow)"),c.push(""),i&&s!=="off"&&(c.push(E(s)),c.push("")),l.length>0){c.push("### Recent commits");for(const a of l)c.push(`- \`${a.hash}\` _${a.date}_ ${a.subject}`);c.push("")}if(d.length>0){c.push("### Recent memory");for(const a of d){const h=a.file?` (\`${a.file}${a.line?":"+a.line:""}\`)`:"",f=(a.msg||a.summary||"").replace(/\n/g," "),b=r&&f.length>r?f.slice(0,r).trimEnd()+"\u2026":f;c.push(`- \u{1F525} ${_[a.type]||"\xB7"} **${a.type||"note"}**${h}: ${b}`)}c.push("")}return p.length===0&&l.length===0&&c.push('_No entries yet. They\'ll appear here as you and your AI tools log them \u2014 run `infernoflow log "..."` or call `amp_write` from any MCP-aware AI._'),c.push(m),c.join(`
14
- `)}function L(e){const o=A(x(e)),t=O(e,o),n=i=>String(i).replace(/\\/g,"/"),r=new Set(o.targets.map(n)),s=[];for(const i of w){const p=y.join(e,i);try{if(r.has(n(i))){const l=I(p,t);s.push({rel:i,...l})}else T(p).stripped&&s.push({rel:i,stripped:!0})}catch(l){s.push({rel:i,error:l.message})}}return s}export{L as refreshRuleFilesFromMemory,A as resolveInjectionSettings,B as writeInitRuleFiles};
12
+ `+n;return u.writeFileSync(e,d,"utf8"),{created:!1,updated:!0}}const i=n.slice(0,r),p=n.slice(s+m.length),l=i+o+p;return l===n?{created:!1,updated:!1}:(u.writeFileSync(e,l,"utf8"),{created:!1,updated:!0})}function Y(e){const{protocolStyle:o}=A(x(e)),t=R(o),n=[];for(const r of w){const s=y.join(e,r);try{const i=I(s,t);n.push({rel:r,...i})}catch(i){n.push({rel:r,error:i.message})}}return n}function P(e){return v(e)}function O(e,o=10){try{return j(`git log --pretty=format:"%h%x09%ad%x09%s" --date=short -n ${o}`,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
13
+ `).filter(Boolean).map(n=>{const[r,s,i]=n.split(" ");return{hash:(r||"").slice(0,7),date:s||"",subject:i||""}})}catch{return[]}}function $(e,o={}){const{maxEntries:t=k,maxCommits:n=C,maxEntryChars:r=S,protocolStyle:s="compact",includeProtocol:i=!0}=o,p=P(e),l=O(e,n);p.sort((a,f)=>{const h=typeof a.ts=="number"?a.ts:Date.parse(a.ts||0);return(typeof f.ts=="number"?f.ts:Date.parse(f.ts||0))-h});const d=p.slice(0,t),_={gotcha:"\u26A0",decision:"\u2713",attempt:"\u2717",note:"\xB7",detection:"\u25CB",pattern:"\u25C7"},c=[];if(c.push(g),c.push("<!-- Auto-managed by infernoflow. Don't edit between these markers. -->"),c.push("## Project memory (infernoflow)"),c.push(""),i&&s!=="off"&&(c.push(E(s)),c.push("")),l.length>0){c.push("### Recent commits");for(const a of l)c.push(`- \`${a.hash}\` _${a.date}_ ${a.subject}`);c.push("")}if(d.length>0){c.push("### Recent memory");for(const a of d){const f=a.file?` (\`${a.file}${a.line?":"+a.line:""}\`)`:"",h=(a.msg||a.summary||"").replace(/\n/g," "),b=r&&h.length>r?h.slice(0,r).trimEnd()+"\u2026":h;c.push(`- \u{1F525} ${_[a.type]||"\xB7"} **${a.type||"note"}**${f}: ${b}`)}c.push("")}return p.length===0&&l.length===0&&c.push('_No entries yet. They\'ll appear here as you and your AI tools log them \u2014 run `infernoflow log "..."` or call `amp_write` from any MCP-aware AI._'),c.push(m),c.join(`
14
+ `)}function X(e){T(e);const o=A(x(e)),t=$(e,o),n=i=>String(i).replace(/\\/g,"/"),r=new Set(o.targets.map(n)),s=[];for(const i of w){const p=y.join(e,i);try{if(r.has(n(i))){const l=I(p,t);s.push({rel:i,...l})}else F(p).stripped&&s.push({rel:i,stripped:!0})}catch(l){s.push({rel:i,error:l.message})}}return s}export{X as refreshRuleFilesFromMemory,A as resolveInjectionSettings,Y as writeInitRuleFiles};
@@ -0,0 +1,71 @@
1
+ ---
2
+ name: memory-keeper
3
+ description: >-
4
+ Captures durable session memory into infernoflow. Invoke at a stopping point,
5
+ before context is lost, or whenever the user says "save what we learned",
6
+ "remember this", "checkpoint", or "bookmark this". It sweeps the work for real
7
+ gotchas, decisions-with-a-because, dead ends, and durable preferences; logs the
8
+ ones worth keeping (skipping noise and duplicates); and drops a named bookmark
9
+ when asked or at a milestone. Read-and-write to the local inferno memory only.
10
+ tools: Bash, Read, Grep
11
+ ---
12
+
13
+ You are **memory-keeper**, a specialist that turns a coding session into durable,
14
+ searchable memory using the `infernoflow` CLI. You are the hands that run the
15
+ commands so the main agent doesn't have to. You never touch application code β€”
16
+ you only read context and write memory.
17
+
18
+ ## Operating rule: balanced
19
+
20
+ Capture what genuinely saves future time; skip the noise. A good memory entry is
21
+ something a competent developer (or the next AI session) could NOT infer from
22
+ reading the code and the diff. When in doubt about a real gotcha, log it. When in
23
+ doubt about routine work, skip it.
24
+
25
+ ## Procedure
26
+
27
+ 1. **Confirm memory is initialized.** Run `infernoflow status`. If there is no
28
+ store (`.ai-memory/`), stop and report that the project isn't initialized β€”
29
+ do not run `init` yourself.
30
+
31
+ 2. **Load what's already remembered** so you don't duplicate:
32
+ - `infernoflow log --show 20` β€” recent entries.
33
+ - `infernoflow ask "<topic>"` β€” for each candidate topic, check if it's known.
34
+
35
+ 3. **Identify capture-worthy items** from the context you were given (and, if
36
+ useful, from files via Read/Grep). Sort each candidate into one type:
37
+ - **gotcha** β€” behaved contrary to a reasonable expectation and cost time.
38
+ - **decision** β€” a non-obvious choice; include the *because*. Add `--result worked` (or `failed`).
39
+ - **dead end** β€” something tried that did NOT work β†’ `--type gotcha --result failed`.
40
+ - **preference** β€” a durable thing the user wants across sessions.
41
+
42
+ 4. **Log each kept item**, one specific sentence per entry, tagged for tracing:
43
+ ```
44
+ infernoflow log "API expects multipart/form-data, rejects application/json" --type gotcha --source memory-keeper --quiet
45
+ infernoflow log "axios over fetch β€” needed upload progress events" --type decision --result worked --source memory-keeper --quiet
46
+ infernoflow log "tried chunked streaming upload, server rejected it" --type gotcha --result failed --source memory-keeper --quiet
47
+ infernoflow log "user prefers inline error handling over wrapper utils" --type preference --source memory-keeper --quiet
48
+ ```
49
+
50
+ 5. **Bookmark** when the user asked for one, at a milestone, or before a risky
51
+ change (on Claude Code this auto-harvests the recent transcript):
52
+ ```
53
+ infernoflow bookmark "auth flow works end to end"
54
+ infernoflow bookmark "before the state refactor" --note "current: context provider per feature"
55
+ ```
56
+
57
+ 6. **Report back** concisely to the main agent:
58
+ - What you logged (one line each, with type).
59
+ - What you deliberately skipped and why (dupe / obvious / routine).
60
+ - Any bookmark dropped.
61
+
62
+ ## Never
63
+ - Never invent entries. Capture only what actually happened in this session β€”
64
+ if you weren't told it and can't verify it on disk, don't log it.
65
+ - Never log secrets, tokens, credentials, or personal data.
66
+ - Never re-log something `infernoflow ask` shows is already captured.
67
+ - Never edit source code, run builds, or run destructive git/rm commands.
68
+ - Never batch several distinct insights into one entry β€” one insight per log.
69
+
70
+ Keep the whole pass fast and quiet. Your value is a clean, deduped memory the
71
+ next session inherits β€” not volume.
@@ -1,337 +1,337 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Cursor hook: capture agent output for infernoflow.
4
- *
5
- * Two jobs in one:
6
- * 1. Always append agent text to inferno/CONTEXT.draft.md (existing behaviour)
7
- * 2. When infernoflow is waiting (inferno/agent-prompt.md exists),
8
- * extract the JSON block from the agent reply and write it to
9
- * inferno/agent-response.json so infernoflow picks it up automatically.
10
- *
11
- * Trigger in .cursor/hooks.json:
12
- * afterAgentResponse β†’ { text }
13
- * stop β†’ { status, loop_count, ... } (--agent-stop flag)
14
- *
15
- * Never fail closed: errors go to stderr; stdout is {} for Cursor.
16
- */
17
- import * as fs from "node:fs";
18
- import * as path from "node:path";
19
- import { spawnSync } from "node:child_process";
20
-
21
- /** Keep in sync with templates/scripts/inferno-promote-draft.mjs */
22
- const DRAFT_HEADER = `# CONTEXT draft (gitignored)
23
- Auto-captured by Cursor hooks (\`.cursor/hooks/inferno-session-draft.mjs\`). **Not product truth** β€” review, then run \`npm run inferno:promote-draft\` or \`infernoflow context\`.
24
- ---
25
- `;
26
-
27
- const MAX_MESSAGE_CHARS = 120_000;
28
- const MAX_FILE_BYTES = 280_000;
29
-
30
- // ── paths ──────────────────────────────────────────────────────────────────
31
-
32
- function projectRoot() {
33
- return process.cwd();
34
- }
35
-
36
- function draftPath() {
37
- return path.join(projectRoot(), "inferno", "CONTEXT.draft.md");
38
- }
39
-
40
- function agentPromptPath() {
41
- return path.join(projectRoot(), "inferno", "agent-prompt.md");
42
- }
43
-
44
- function agentResponsePath() {
45
- return path.join(projectRoot(), "inferno", "agent-response.json");
46
- }
47
-
48
- // ── CONTEXT.draft.md helpers ───────────────────────────────────────────────
49
-
50
- function ensureDraftFile(file) {
51
- if (!fs.existsSync(file)) {
52
- fs.mkdirSync(path.dirname(file), { recursive: true });
53
- fs.writeFileSync(file, DRAFT_HEADER, "utf8");
54
- }
55
- }
56
-
57
- function trimFile(file) {
58
- const raw = fs.readFileSync(file, "utf8");
59
- if (Buffer.byteLength(raw, "utf8") <= MAX_FILE_BYTES) return;
60
- const keep = raw.slice(-Math.floor(MAX_FILE_BYTES * 0.85));
61
- const idx = keep.indexOf("\n### ");
62
- const body = idx === -1 ? keep : keep.slice(idx);
63
- fs.writeFileSync(
64
- file,
65
- `${DRAFT_HEADER}\n_(older capture trimmed for size)_\n\n${body}`,
66
- "utf8",
67
- );
68
- }
69
-
70
- function appendBlock(file, block) {
71
- ensureDraftFile(file);
72
- fs.appendFileSync(file, block, "utf8");
73
- trimFile(file);
74
- }
75
-
76
- // ── JSON extraction ────────────────────────────────────────────────────────
77
-
78
- function extractJsonFromText(text) {
79
- // 1. fenced code block
80
- const fenceMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/);
81
- if (fenceMatch) {
82
- const candidate = fenceMatch[1].trim();
83
- try {
84
- JSON.parse(candidate);
85
- return candidate;
86
- } catch {}
87
- }
88
-
89
- // 2. largest bare JSON object in the text
90
- const jsonMatch = text.match(/\{[\s\S]*\}/);
91
- if (jsonMatch) {
92
- try {
93
- JSON.parse(jsonMatch[0]);
94
- return jsonMatch[0];
95
- } catch {}
96
- }
97
-
98
- return null;
99
- }
100
-
101
- // ── bridge: write agent-response.json if infernoflow is waiting ────────────
102
-
103
- function maybeWriteAgentResponse(text) {
104
- const promptFile = agentPromptPath();
105
- const responseFile = agentResponsePath();
106
-
107
- if (!fs.existsSync(promptFile)) return false;
108
-
109
- const json = extractJsonFromText(text);
110
- if (!json) {
111
- process.stderr.write(
112
- "[inferno-session-draft] infernoflow waiting but no JSON found in agent reply\n",
113
- );
114
- return false;
115
- }
116
-
117
- fs.writeFileSync(responseFile, json, "utf8");
118
- try {
119
- fs.unlinkSync(promptFile);
120
- } catch {}
121
-
122
- process.stderr.write(
123
- "[inferno-session-draft] βœ” agent-response.json written β€” infernoflow will continue\n",
124
- );
125
- return true;
126
- }
127
-
128
- // ── stdin ──────────────────────────────────────────────────────────────────
129
-
130
- async function readStdin() {
131
- const chunks = [];
132
- for await (const c of process.stdin) chunks.push(c);
133
- return Buffer.concat(chunks).toString("utf8");
134
- }
135
-
136
- // ── Deterministic trigger capture (beforeSubmitPrompt) ──────────────────────
137
- // Cursor's beforeSubmitPrompt hook hands us the USER's prompt text before it
138
- // goes to the model. The Memory-protocol block already asks the AI to log on
139
- // these signals, but the AI doesn't always obey β€” so this is a deterministic
140
- // backstop: if the prompt itself contains a trouble signal (!!, retry, "not
141
- // working", …) we write an `attempt` entry ourselves. Bounded hard against
142
- // noise: a 90s cooldown + identical-prompt dedupe, so a frustrated burst of
143
- // "still broken!! retry!!" produces ONE entry, not ten.
144
- const TRIGGER_RES = [
145
- /(?:^|\s)!!+/,
146
- /\bretry(?:ing)?\b/i,
147
- /\bnot working\b/i,
148
- /\bstill (?:broken|failing|not working|doesn['’]?t)\b/i,
149
- /\bsame (?:error|issue|problem)\b/i,
150
- /\bno change\b/i,
151
- /\bdoesn['’]?t work\b/i,
152
- ];
153
-
154
- // Deterministic BOOKMARK triggers β€” an explicit "bookmark this" is an intentional
155
- // resume point (not a trouble signal), so it takes precedence and drops a real
156
- // bookmark (which auto-captures the session transcript). No AI cooperation needed.
157
- const BOOKMARK_RES = [
158
- /\bbookmark (?:this|it|here)(?: point)?\b/i,
159
- /\bmark this (?:point|spot|moment|here)\b/i,
160
- /\bsave (?:this )?(?:point|checkpoint|resume point)\b/i,
161
- ];
162
-
163
- /** Strip the trigger phrase to reuse the rest of the prompt as the bookmark label. */
164
- function deriveBookmarkLabel(prompt) {
165
- const label = prompt
166
- .replace(/\bbookmark (?:this|it|here)(?: point)?\b/ig, "")
167
- .replace(/\bmark this (?:point|spot|moment|here)\b/ig, "")
168
- .replace(/\bsave (?:this )?(?:point|checkpoint|resume point)\b/ig, "")
169
- .replace(/[\s:.!,–—-]+/g, " ")
170
- .replace(/\s+/g, " ")
171
- .trim();
172
- return (label.slice(0, 80).trim()) || "Session bookmark";
173
- }
174
-
175
- function memoryRootExists() {
176
- return fs.existsSync(path.join(projectRoot(), ".ai-memory")) ||
177
- fs.existsSync(path.join(projectRoot(), "inferno"));
178
- }
179
-
180
- function triggerStatePath() {
181
- return path.join(projectRoot(), ".ai-memory", ".trigger-state.json");
182
- }
183
-
184
- function cheapHash(s) {
185
- let h = 0;
186
- for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
187
- return String(h);
188
- }
189
-
190
- function handleBookmarkTrigger(prompt) {
191
- const now = Date.now();
192
- const stateFile = triggerStatePath();
193
- let state = {};
194
- try { state = JSON.parse(fs.readFileSync(stateFile, "utf8")); } catch {}
195
- const h = cheapHash(prompt.slice(0, 200));
196
- if (state.lastBmHash === h) return; // same prompt β€” don't double-fire
197
-
198
- const label = deriveBookmarkLabel(prompt);
199
- let wrote = false;
200
- try {
201
- // The `bookmark` command (no --marker) auto-captures the session transcript
202
- // as the resume point. Needs infernoflow >= 0.44.10 on PATH; if the global
203
- // CLI is older / missing, this no-ops and the AI's amp_bookmark path covers it.
204
- const bin = process.platform === "win32" ? "infernoflow.cmd" : "infernoflow";
205
- const r = spawnSync(bin, ["bookmark", label], {
206
- cwd: projectRoot(), encoding: "utf8", timeout: 12000, shell: process.platform === "win32",
207
- });
208
- wrote = r.status === 0;
209
- } catch { /* CLI unavailable β€” skip */ }
210
-
211
- if (wrote) {
212
- try { fs.writeFileSync(stateFile, JSON.stringify({ ...state, lastBmHash: h }), "utf8"); } catch {}
213
- process.stderr.write("[inferno-session-draft] auto-bookmarked resume point\n");
214
- }
215
- }
216
-
217
- function handleUserPrompt(text) {
218
- const trimmed = (text || "").trim();
219
- if (!trimmed) return;
220
- if (!memoryRootExists()) return; // only inside infernoflow projects
221
-
222
- // Bookmark trigger takes precedence β€” "bookmark this" is intentional, not trouble.
223
- if (BOOKMARK_RES.some((re) => re.test(trimmed))) { handleBookmarkTrigger(trimmed); return; }
224
-
225
- if (!TRIGGER_RES.some((re) => re.test(trimmed))) return;
226
-
227
- const now = Date.now();
228
- const stateFile = triggerStatePath();
229
- let state = {};
230
- try { state = JSON.parse(fs.readFileSync(stateFile, "utf8")); } catch {}
231
- const h = cheapHash(trimmed.slice(0, 200));
232
- const COOLDOWN_MS = 90_000;
233
- if (state.lastHash === h) return; // exact same prompt β€” skip
234
- if (state.lastTs && now - state.lastTs < COOLDOWN_MS) return; // rate-limit
235
-
236
- const msg = "Auto-trigger β€” user signalled trouble: " +
237
- trimmed.replace(/\s+/g, " ").slice(0, 180);
238
-
239
- // Prefer the CLI (correct id / branch routing / AMP shape); fall back to a
240
- // direct sessions.jsonl append so capture still works without a global CLI.
241
- let wrote = false;
242
- try {
243
- const bin = process.platform === "win32" ? "infernoflow.cmd" : "infernoflow";
244
- const r = spawnSync(bin, ["log", msg, "--type", "attempt", "--source", "cursor-trigger", "--tags", "auto-trigger"], {
245
- cwd: projectRoot(), encoding: "utf8", timeout: 8000, shell: process.platform === "win32",
246
- });
247
- wrote = r.status === 0;
248
- } catch { /* fall through to direct write */ }
249
- if (!wrote) {
250
- try {
251
- const sess = path.join(projectRoot(), ".ai-memory", "sessions.jsonl");
252
- fs.mkdirSync(path.dirname(sess), { recursive: true });
253
- const entry = { type: "attempt", msg, ts: now, id: "amp_hook_" + now.toString(36), source: "cursor-trigger", tags: ["auto-trigger"], meta: { agent: "cursor-hook" } };
254
- fs.appendFileSync(sess, JSON.stringify(entry) + "\n", "utf8");
255
- wrote = true;
256
- } catch { /* best effort */ }
257
- }
258
-
259
- if (wrote) {
260
- try { fs.writeFileSync(stateFile, JSON.stringify({ ...state, lastTs: now, lastHash: h }), "utf8"); } catch {}
261
- process.stderr.write("[inferno-session-draft] auto-captured trigger to memory\n");
262
- }
263
- }
264
-
265
- // ── main ───────────────────────────────────────────────────────────────────
266
-
267
- function main() {
268
- const agentStop = process.argv.includes("--agent-stop");
269
-
270
- readStdin()
271
- .then((raw) => {
272
- let data = {};
273
- try {
274
- data = raw.trim() ? JSON.parse(raw) : {};
275
- } catch (e) {
276
- console.error("[inferno-session-draft] stdin JSON parse:", e.message);
277
- console.log("{}");
278
- process.exit(0);
279
- return;
280
- }
281
-
282
- // beforeSubmitPrompt: deterministic trigger capture on the USER's prompt.
283
- if (process.argv.includes("--user-prompt")) {
284
- const t = typeof data.prompt === "string" ? data.prompt
285
- : typeof data.text === "string" ? data.text : "";
286
- try { handleUserPrompt(t); } catch (e) { console.error("[inferno-session-draft] trigger:", e?.message); }
287
- console.log("{}");
288
- process.exit(0);
289
- return;
290
- }
291
-
292
- const file = draftPath();
293
-
294
- if (agentStop) {
295
- const status = data.status ?? "unknown";
296
- const loop = data.loop_count ?? 0;
297
- appendBlock(
298
- file,
299
- `\n### _agent stop_ (${new Date().toISOString()})\n\nstatus: \`${status}\` Β· loop_count: ${loop}\n\n---\n`,
300
- );
301
- console.log("{}");
302
- process.exit(0);
303
- return;
304
- }
305
-
306
- const text = typeof data.text === "string" ? data.text : "";
307
- if (!text.trim()) {
308
- console.log("{}");
309
- process.exit(0);
310
- return;
311
- }
312
-
313
- // Job 2: feed infernoflow's file-based bridge if it is waiting
314
- maybeWriteAgentResponse(text);
315
-
316
- // Job 1: always append to CONTEXT.draft.md
317
- const clipped =
318
- text.length > MAX_MESSAGE_CHARS
319
- ? `${text.slice(0, MAX_MESSAGE_CHARS)}\n\n_…trimmed (${text.length - MAX_MESSAGE_CHARS} chars omitted)_\n`
320
- : text;
321
-
322
- appendBlock(
323
- file,
324
- `\n### Assistant message (${new Date().toISOString()})\n\n${clipped}\n\n---\n`,
325
- );
326
-
327
- console.log("{}");
328
- process.exit(0);
329
- })
330
- .catch((e) => {
331
- console.error("[inferno-session-draft]", e);
332
- console.log("{}");
333
- process.exit(0);
334
- });
335
- }
336
-
337
- main();
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Cursor hook: capture agent output for infernoflow.
4
+ *
5
+ * Two jobs in one:
6
+ * 1. Always append agent text to inferno/CONTEXT.draft.md (existing behaviour)
7
+ * 2. When infernoflow is waiting (inferno/agent-prompt.md exists),
8
+ * extract the JSON block from the agent reply and write it to
9
+ * inferno/agent-response.json so infernoflow picks it up automatically.
10
+ *
11
+ * Trigger in .cursor/hooks.json:
12
+ * afterAgentResponse β†’ { text }
13
+ * stop β†’ { status, loop_count, ... } (--agent-stop flag)
14
+ *
15
+ * Never fail closed: errors go to stderr; stdout is {} for Cursor.
16
+ */
17
+ import * as fs from "node:fs";
18
+ import * as path from "node:path";
19
+ import { spawnSync } from "node:child_process";
20
+
21
+ /** Keep in sync with templates/scripts/inferno-promote-draft.mjs */
22
+ const DRAFT_HEADER = `# CONTEXT draft (gitignored)
23
+ Auto-captured by Cursor hooks (\`.cursor/hooks/inferno-session-draft.mjs\`). **Not product truth** β€” review, then run \`npm run inferno:promote-draft\` or \`infernoflow context\`.
24
+ ---
25
+ `;
26
+
27
+ const MAX_MESSAGE_CHARS = 120_000;
28
+ const MAX_FILE_BYTES = 280_000;
29
+
30
+ // ── paths ──────────────────────────────────────────────────────────────────
31
+
32
+ function projectRoot() {
33
+ return process.cwd();
34
+ }
35
+
36
+ function draftPath() {
37
+ return path.join(projectRoot(), "inferno", "CONTEXT.draft.md");
38
+ }
39
+
40
+ function agentPromptPath() {
41
+ return path.join(projectRoot(), "inferno", "agent-prompt.md");
42
+ }
43
+
44
+ function agentResponsePath() {
45
+ return path.join(projectRoot(), "inferno", "agent-response.json");
46
+ }
47
+
48
+ // ── CONTEXT.draft.md helpers ───────────────────────────────────────────────
49
+
50
+ function ensureDraftFile(file) {
51
+ if (!fs.existsSync(file)) {
52
+ fs.mkdirSync(path.dirname(file), { recursive: true });
53
+ fs.writeFileSync(file, DRAFT_HEADER, "utf8");
54
+ }
55
+ }
56
+
57
+ function trimFile(file) {
58
+ const raw = fs.readFileSync(file, "utf8");
59
+ if (Buffer.byteLength(raw, "utf8") <= MAX_FILE_BYTES) return;
60
+ const keep = raw.slice(-Math.floor(MAX_FILE_BYTES * 0.85));
61
+ const idx = keep.indexOf("\n### ");
62
+ const body = idx === -1 ? keep : keep.slice(idx);
63
+ fs.writeFileSync(
64
+ file,
65
+ `${DRAFT_HEADER}\n_(older capture trimmed for size)_\n\n${body}`,
66
+ "utf8",
67
+ );
68
+ }
69
+
70
+ function appendBlock(file, block) {
71
+ ensureDraftFile(file);
72
+ fs.appendFileSync(file, block, "utf8");
73
+ trimFile(file);
74
+ }
75
+
76
+ // ── JSON extraction ────────────────────────────────────────────────────────
77
+
78
+ function extractJsonFromText(text) {
79
+ // 1. fenced code block
80
+ const fenceMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/);
81
+ if (fenceMatch) {
82
+ const candidate = fenceMatch[1].trim();
83
+ try {
84
+ JSON.parse(candidate);
85
+ return candidate;
86
+ } catch {}
87
+ }
88
+
89
+ // 2. largest bare JSON object in the text
90
+ const jsonMatch = text.match(/\{[\s\S]*\}/);
91
+ if (jsonMatch) {
92
+ try {
93
+ JSON.parse(jsonMatch[0]);
94
+ return jsonMatch[0];
95
+ } catch {}
96
+ }
97
+
98
+ return null;
99
+ }
100
+
101
+ // ── bridge: write agent-response.json if infernoflow is waiting ────────────
102
+
103
+ function maybeWriteAgentResponse(text) {
104
+ const promptFile = agentPromptPath();
105
+ const responseFile = agentResponsePath();
106
+
107
+ if (!fs.existsSync(promptFile)) return false;
108
+
109
+ const json = extractJsonFromText(text);
110
+ if (!json) {
111
+ process.stderr.write(
112
+ "[inferno-session-draft] infernoflow waiting but no JSON found in agent reply\n",
113
+ );
114
+ return false;
115
+ }
116
+
117
+ fs.writeFileSync(responseFile, json, "utf8");
118
+ try {
119
+ fs.unlinkSync(promptFile);
120
+ } catch {}
121
+
122
+ process.stderr.write(
123
+ "[inferno-session-draft] βœ” agent-response.json written β€” infernoflow will continue\n",
124
+ );
125
+ return true;
126
+ }
127
+
128
+ // ── stdin ──────────────────────────────────────────────────────────────────
129
+
130
+ async function readStdin() {
131
+ const chunks = [];
132
+ for await (const c of process.stdin) chunks.push(c);
133
+ return Buffer.concat(chunks).toString("utf8");
134
+ }
135
+
136
+ // ── Deterministic trigger capture (beforeSubmitPrompt) ──────────────────────
137
+ // Cursor's beforeSubmitPrompt hook hands us the USER's prompt text before it
138
+ // goes to the model. The Memory-protocol block already asks the AI to log on
139
+ // these signals, but the AI doesn't always obey β€” so this is a deterministic
140
+ // backstop: if the prompt itself contains a trouble signal (!!, retry, "not
141
+ // working", …) we write an `attempt` entry ourselves. Bounded hard against
142
+ // noise: a 90s cooldown + identical-prompt dedupe, so a frustrated burst of
143
+ // "still broken!! retry!!" produces ONE entry, not ten.
144
+ const TRIGGER_RES = [
145
+ /(?:^|\s)!!+/,
146
+ /\bretry(?:ing)?\b/i,
147
+ /\bnot working\b/i,
148
+ /\bstill (?:broken|failing|not working|doesn['’]?t)\b/i,
149
+ /\bsame (?:error|issue|problem)\b/i,
150
+ /\bno change\b/i,
151
+ /\bdoesn['’]?t work\b/i,
152
+ ];
153
+
154
+ // Deterministic BOOKMARK triggers β€” an explicit "bookmark this" is an intentional
155
+ // resume point (not a trouble signal), so it takes precedence and drops a real
156
+ // bookmark (which auto-captures the session transcript). No AI cooperation needed.
157
+ const BOOKMARK_RES = [
158
+ /\bbookmark (?:this|it|here)(?: point)?\b/i,
159
+ /\bmark this (?:point|spot|moment|here)\b/i,
160
+ /\bsave (?:this )?(?:point|checkpoint|resume point)\b/i,
161
+ ];
162
+
163
+ /** Strip the trigger phrase to reuse the rest of the prompt as the bookmark label. */
164
+ function deriveBookmarkLabel(prompt) {
165
+ const label = prompt
166
+ .replace(/\bbookmark (?:this|it|here)(?: point)?\b/ig, "")
167
+ .replace(/\bmark this (?:point|spot|moment|here)\b/ig, "")
168
+ .replace(/\bsave (?:this )?(?:point|checkpoint|resume point)\b/ig, "")
169
+ .replace(/[\s:.!,–—-]+/g, " ")
170
+ .replace(/\s+/g, " ")
171
+ .trim();
172
+ return (label.slice(0, 80).trim()) || "Session bookmark";
173
+ }
174
+
175
+ function memoryRootExists() {
176
+ return fs.existsSync(path.join(projectRoot(), ".ai-memory")) ||
177
+ fs.existsSync(path.join(projectRoot(), "inferno"));
178
+ }
179
+
180
+ function triggerStatePath() {
181
+ return path.join(projectRoot(), ".ai-memory", ".trigger-state.json");
182
+ }
183
+
184
+ function cheapHash(s) {
185
+ let h = 0;
186
+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
187
+ return String(h);
188
+ }
189
+
190
+ function handleBookmarkTrigger(prompt) {
191
+ const now = Date.now();
192
+ const stateFile = triggerStatePath();
193
+ let state = {};
194
+ try { state = JSON.parse(fs.readFileSync(stateFile, "utf8")); } catch {}
195
+ const h = cheapHash(prompt.slice(0, 200));
196
+ if (state.lastBmHash === h) return; // same prompt β€” don't double-fire
197
+
198
+ const label = deriveBookmarkLabel(prompt);
199
+ let wrote = false;
200
+ try {
201
+ // The `bookmark` command (no --marker) auto-captures the session transcript
202
+ // as the resume point. Needs infernoflow >= 0.44.10 on PATH; if the global
203
+ // CLI is older / missing, this no-ops and the AI's amp_bookmark path covers it.
204
+ const bin = process.platform === "win32" ? "infernoflow.cmd" : "infernoflow";
205
+ const r = spawnSync(bin, ["bookmark", label], {
206
+ cwd: projectRoot(), encoding: "utf8", timeout: 12000, shell: process.platform === "win32",
207
+ });
208
+ wrote = r.status === 0;
209
+ } catch { /* CLI unavailable β€” skip */ }
210
+
211
+ if (wrote) {
212
+ try { fs.writeFileSync(stateFile, JSON.stringify({ ...state, lastBmHash: h }), "utf8"); } catch {}
213
+ process.stderr.write("[inferno-session-draft] auto-bookmarked resume point\n");
214
+ }
215
+ }
216
+
217
+ function handleUserPrompt(text) {
218
+ const trimmed = (text || "").trim();
219
+ if (!trimmed) return;
220
+ if (!memoryRootExists()) return; // only inside infernoflow projects
221
+
222
+ // Bookmark trigger takes precedence β€” "bookmark this" is intentional, not trouble.
223
+ if (BOOKMARK_RES.some((re) => re.test(trimmed))) { handleBookmarkTrigger(trimmed); return; }
224
+
225
+ if (!TRIGGER_RES.some((re) => re.test(trimmed))) return;
226
+
227
+ const now = Date.now();
228
+ const stateFile = triggerStatePath();
229
+ let state = {};
230
+ try { state = JSON.parse(fs.readFileSync(stateFile, "utf8")); } catch {}
231
+ const h = cheapHash(trimmed.slice(0, 200));
232
+ const COOLDOWN_MS = 90_000;
233
+ if (state.lastHash === h) return; // exact same prompt β€” skip
234
+ if (state.lastTs && now - state.lastTs < COOLDOWN_MS) return; // rate-limit
235
+
236
+ const msg = "Auto-trigger β€” user signalled trouble: " +
237
+ trimmed.replace(/\s+/g, " ").slice(0, 180);
238
+
239
+ // Prefer the CLI (correct id / branch routing / AMP shape); fall back to a
240
+ // direct sessions.jsonl append so capture still works without a global CLI.
241
+ let wrote = false;
242
+ try {
243
+ const bin = process.platform === "win32" ? "infernoflow.cmd" : "infernoflow";
244
+ const r = spawnSync(bin, ["log", msg, "--type", "attempt", "--source", "cursor-trigger", "--tags", "auto-trigger"], {
245
+ cwd: projectRoot(), encoding: "utf8", timeout: 8000, shell: process.platform === "win32",
246
+ });
247
+ wrote = r.status === 0;
248
+ } catch { /* fall through to direct write */ }
249
+ if (!wrote) {
250
+ try {
251
+ const sess = path.join(projectRoot(), ".ai-memory", "sessions.jsonl");
252
+ fs.mkdirSync(path.dirname(sess), { recursive: true });
253
+ const entry = { type: "attempt", msg, ts: now, id: "amp_hook_" + now.toString(36), source: "cursor-trigger", tags: ["auto-trigger"], meta: { agent: "cursor-hook" } };
254
+ fs.appendFileSync(sess, JSON.stringify(entry) + "\n", "utf8");
255
+ wrote = true;
256
+ } catch { /* best effort */ }
257
+ }
258
+
259
+ if (wrote) {
260
+ try { fs.writeFileSync(stateFile, JSON.stringify({ ...state, lastTs: now, lastHash: h }), "utf8"); } catch {}
261
+ process.stderr.write("[inferno-session-draft] auto-captured trigger to memory\n");
262
+ }
263
+ }
264
+
265
+ // ── main ───────────────────────────────────────────────────────────────────
266
+
267
+ function main() {
268
+ const agentStop = process.argv.includes("--agent-stop");
269
+
270
+ readStdin()
271
+ .then((raw) => {
272
+ let data = {};
273
+ try {
274
+ data = raw.trim() ? JSON.parse(raw) : {};
275
+ } catch (e) {
276
+ console.error("[inferno-session-draft] stdin JSON parse:", e.message);
277
+ console.log("{}");
278
+ process.exit(0);
279
+ return;
280
+ }
281
+
282
+ // beforeSubmitPrompt: deterministic trigger capture on the USER's prompt.
283
+ if (process.argv.includes("--user-prompt")) {
284
+ const t = typeof data.prompt === "string" ? data.prompt
285
+ : typeof data.text === "string" ? data.text : "";
286
+ try { handleUserPrompt(t); } catch (e) { console.error("[inferno-session-draft] trigger:", e?.message); }
287
+ console.log("{}");
288
+ process.exit(0);
289
+ return;
290
+ }
291
+
292
+ const file = draftPath();
293
+
294
+ if (agentStop) {
295
+ const status = data.status ?? "unknown";
296
+ const loop = data.loop_count ?? 0;
297
+ appendBlock(
298
+ file,
299
+ `\n### _agent stop_ (${new Date().toISOString()})\n\nstatus: \`${status}\` Β· loop_count: ${loop}\n\n---\n`,
300
+ );
301
+ console.log("{}");
302
+ process.exit(0);
303
+ return;
304
+ }
305
+
306
+ const text = typeof data.text === "string" ? data.text : "";
307
+ if (!text.trim()) {
308
+ console.log("{}");
309
+ process.exit(0);
310
+ return;
311
+ }
312
+
313
+ // Job 2: feed infernoflow's file-based bridge if it is waiting
314
+ maybeWriteAgentResponse(text);
315
+
316
+ // Job 1: always append to CONTEXT.draft.md
317
+ const clipped =
318
+ text.length > MAX_MESSAGE_CHARS
319
+ ? `${text.slice(0, MAX_MESSAGE_CHARS)}\n\n_…trimmed (${text.length - MAX_MESSAGE_CHARS} chars omitted)_\n`
320
+ : text;
321
+
322
+ appendBlock(
323
+ file,
324
+ `\n### Assistant message (${new Date().toISOString()})\n\n${clipped}\n\n---\n`,
325
+ );
326
+
327
+ console.log("{}");
328
+ process.exit(0);
329
+ })
330
+ .catch((e) => {
331
+ console.error("[inferno-session-draft]", e);
332
+ console.log("{}");
333
+ process.exit(0);
334
+ });
335
+ }
336
+
337
+ main();
@@ -0,0 +1,116 @@
1
+ ---
2
+ name: infernoflow-memory
3
+ description: >-
4
+ Persistent cross-session memory for this project via the infernoflow CLI. Use
5
+ whenever you discover a gotcha, make a non-obvious decision, hit a dead end, or
6
+ learn a lasting user preference β€” capture it with `infernoflow log` so the next
7
+ session starts warm instead of cold. Also use to drop a `infernoflow bookmark`
8
+ at natural stopping points or whenever the user says "bookmark this" / "save
9
+ this point", and to load prior memory at the start of work. Triggers: gotcha,
10
+ "that was surprising", "turns out", dead end, "doesn't work", decision, "let's
11
+ go with", "because", preference, "I prefer", bookmark, checkpoint, resume,
12
+ "where were we", start of a work session in a repo that has an infernoflow memory store (.ai-memory/).
13
+ ---
14
+
15
+ # infernoflow memory
16
+
17
+ This project uses **infernoflow** β€” a local, git-tracked memory layer that stores
18
+ what you can't infer from the code: the gotchas you hit, the decisions you made
19
+ *and why*, the dead ends you already tried, and the user's durable preferences.
20
+ Memory lives in `inferno/sessions.jsonl` and is auto-injected into the rule files
21
+ this IDE already reads. Your job is to keep that memory alive so the next session
22
+ (yours or a teammate's) starts warm.
23
+
24
+ Capture is **balanced**: log the things that genuinely save future time, and skip
25
+ the noise. When unsure, prefer logging a real gotcha over staying silent β€” but
26
+ never log routine steps or anything obvious from reading the code.
27
+
28
+ ## Start warm
29
+
30
+ At the start of substantive work in a project that has an infernoflow memory store
31
+ (`.ai-memory/`), load
32
+ prior memory before diving in:
33
+
34
+ ```
35
+ infernoflow recap
36
+ ```
37
+
38
+ If you're looking for something specific ("did we decide on the auth approach?"),
39
+ ask memory directly:
40
+
41
+ ```
42
+ infernoflow ask "auth approach"
43
+ ```
44
+
45
+ Do this once per session, not repeatedly.
46
+
47
+ ## Capture as you work
48
+
49
+ Run `infernoflow log` the moment one of these happens β€” capture it right away,
50
+ while the detail is fresh, not at the end:
51
+
52
+ **Gotcha** β€” something behaved contrary to a reasonable expectation and cost time:
53
+ ```
54
+ infernoflow log "API expects multipart/form-data, rejects application/json" --type gotcha
55
+ ```
56
+
57
+ **Decision with a because** β€” a non-obvious choice a future reader would question:
58
+ ```
59
+ infernoflow log "axios over fetch β€” needed upload progress events" --type decision --result worked
60
+ ```
61
+
62
+ **Dead end** β€” something you tried that did NOT work, so nobody repeats it:
63
+ ```
64
+ infernoflow log "tried streaming upload, server rejected chunked transfer" --type gotcha --result failed
65
+ ```
66
+
67
+ **Preference** β€” a durable thing the user wants, stated or clearly implied:
68
+ ```
69
+ infernoflow log "user prefers inline error handling over try/catch wrappers" --type preference
70
+ ```
71
+
72
+ Keep each message to one specific sentence. Always include the *because* for a
73
+ decision. In non-interactive/automation contexts add `--quiet`.
74
+
75
+ ### Do log
76
+ - A gotcha that would waste time again (config quirk, undocumented API behavior, env-specific bug).
77
+ - A decision whose reasoning isn't visible in the diff.
78
+ - A dead end / abandoned approach.
79
+ - A user preference that should hold across sessions.
80
+
81
+ ### Do NOT log
82
+ - Routine steps or anything obvious from reading the code.
83
+ - Secrets, tokens, credentials, or personal data.
84
+ - Duplicates β€” if it's already in memory (`infernoflow ask`), don't repeat it.
85
+ - Vague notes ("fixed a bug") with no reusable signal.
86
+
87
+ ## Bookmark at stopping points
88
+
89
+ A bookmark is a named resume point. On Claude Code it auto-harvests the recent
90
+ transcript into the bookmark's context β€” deterministic, no AI calls.
91
+
92
+ Drop one:
93
+ - **Always** when the user says "bookmark this", "save this point", "checkpoint", or similar.
94
+ - At a **natural milestone** ("auth flow works end to end").
95
+ - **Before a risky change** ("before the state-management refactor") as a safety net.
96
+
97
+ ```
98
+ infernoflow bookmark "auth flow works end to end"
99
+ infernoflow bookmark "before the SP refactor" --note "current approach: context provider per feature"
100
+ ```
101
+
102
+ Recall / list / remove:
103
+ ```
104
+ infernoflow bookmark list
105
+ infernoflow bookmark show "auth flow"
106
+ infernoflow bookmark rm "auth flow"
107
+ ```
108
+
109
+ When the user returns and asks "where were we?", run `infernoflow bookmark list`
110
+ (or `infernoflow recap`) and continue from the most relevant marker.
111
+
112
+ ## Notes
113
+ - All commands are local and safe; memory is a plain JSONL file under `inferno/`.
114
+ - If a project has no infernoflow memory store (`.ai-memory/`), this skill does not
115
+ apply β€” memory is opt-in per repo (`infernoflow init` creates it).
116
+ - One log per distinct insight; batching many into one line loses searchability.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "infernoflow",
3
- "version": "0.44.15",
3
+ "version": "0.44.17",
4
4
  "description": "Persistent memory for AI coding sessions \u2014 captures what agents can't infer from code alone. Works with Copilot, Cursor, Claude, and Windsurf.",
5
5
  "type": "module",
6
6
  "bin": {