agentix-cli 0.89.0 → 0.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/{App-BSGDYHRD.js → App-LC34QQPN.js} +2 -2
  2. package/dist/{ChatApp-K57DBCDT.js → ChatApp-FB72AK7M.js} +2 -2
  3. package/dist/{agent-6MTUM5DR.js → agent-OZ4XFAD4.js} +2 -2
  4. package/dist/{board-dashboard-GL6GQ32D.js → board-dashboard-YBWSJ7J2.js} +210 -210
  5. package/dist/{board-dashboard-GL6GQ32D.js.map → board-dashboard-YBWSJ7J2.js.map} +1 -1
  6. package/dist/{chunk-ECCPLASB.js → chunk-26UFDYRZ.js} +2 -2
  7. package/dist/{chunk-HQWMWSSE.js → chunk-3GN255MT.js} +2 -2
  8. package/dist/{chunk-7QDAGGOD.js → chunk-3SEFVZA7.js} +2 -2
  9. package/dist/{chunk-DWZYVYZS.js → chunk-3SZ4CU6G.js} +57 -15
  10. package/dist/chunk-3SZ4CU6G.js.map +1 -0
  11. package/dist/{chunk-XVDASTUX.js → chunk-64UK5VG4.js} +2 -2
  12. package/dist/{chunk-N4HFUAPN.js → chunk-A5DFX47N.js} +2 -2
  13. package/dist/{chunk-HOXHUFZB.js → chunk-BEJCSZOQ.js} +2 -2
  14. package/dist/{chunk-BFY4D4RH.js → chunk-BTTQZWYB.js} +2 -2
  15. package/dist/{chunk-I6HCIQCQ.js → chunk-ISIJAZGO.js} +2 -2
  16. package/dist/{chunk-C3VCIEZS.js → chunk-JF5UGNMG.js} +2 -2
  17. package/dist/{chunk-2FLVU2QW.js → chunk-JLCYQZRT.js} +2 -2
  18. package/dist/{chunk-3CHAPGUX.js → chunk-JVQXD35E.js} +195 -194
  19. package/dist/chunk-JVQXD35E.js.map +1 -0
  20. package/dist/{chunk-MZQ5PCLA.js → chunk-LCWE2GHC.js} +2 -2
  21. package/dist/{chunk-7K5SJJUI.js → chunk-LS6KXRXY.js} +2 -2
  22. package/dist/{chunk-KIXDJEGA.js → chunk-MBVRADNG.js} +2 -2
  23. package/dist/{chunk-BUELCBBV.js → chunk-MU4S6LQA.js} +8 -8
  24. package/dist/{chunk-BUELCBBV.js.map → chunk-MU4S6LQA.js.map} +1 -1
  25. package/dist/{chunk-X2F3AVGR.js → chunk-N2OMSKIQ.js} +2 -2
  26. package/dist/{chunk-EUXF2GJY.js → chunk-QYFF2WJ2.js} +2 -2
  27. package/dist/{chunk-PN6XHTG5.js → chunk-RJ7DASOU.js} +4 -4
  28. package/dist/{chunk-PN6XHTG5.js.map → chunk-RJ7DASOU.js.map} +1 -1
  29. package/dist/{chunk-TNR7AI4H.js → chunk-RLXEF2X6.js} +67 -67
  30. package/dist/chunk-RLXEF2X6.js.map +1 -0
  31. package/dist/{chunk-BOENB3IK.js → chunk-TA2BYYNZ.js} +2 -2
  32. package/dist/{chunk-OAA7TNB6.js → chunk-TGN7K7VG.js} +2 -2
  33. package/dist/{chunk-7ADEEHZQ.js → chunk-TS7JDPOY.js} +2 -2
  34. package/dist/{chunk-BYD5B3P3.js → chunk-UVMCAZL7.js} +2 -2
  35. package/dist/{chunk-7OEFPYQJ.js → chunk-UWH7NTGV.js} +2 -2
  36. package/dist/{chunk-54VYZE7A.js → chunk-XSVGD64O.js} +3 -3
  37. package/dist/{chunk-54VYZE7A.js.map → chunk-XSVGD64O.js.map} +1 -1
  38. package/dist/cli.js +1 -1
  39. package/dist/{client-UKLOVDZB.js → client-IPZRCNE7.js} +2 -2
  40. package/dist/{config-WUDWHRT6.js → config-HZTKLB6A.js} +2 -2
  41. package/dist/config-mutator-6S4X6WMU.js +2 -0
  42. package/dist/{doctor-COAIIKLV.js → doctor-BTHIQN7F.js} +2 -2
  43. package/dist/index.d.ts +14 -13
  44. package/dist/index.js +1 -1
  45. package/dist/processes-MMAVAZAC.js +2 -0
  46. package/dist/{program-QKXRASTV.js → program-PURSFZBM.js} +170 -170
  47. package/dist/program-PURSFZBM.js.map +1 -0
  48. package/dist/{promote-B7FGHUFA.js → promote-RDXNGZKX.js} +2 -2
  49. package/dist/{query-ZSVAGGSM.js → query-OGMNU45Y.js} +2 -2
  50. package/dist/{registry-4DWWYWDR.js → registry-LKIOKDIG.js} +2 -2
  51. package/dist/{request-planner-DSXXT75B.js → request-planner-EP6QJAK5.js} +2 -2
  52. package/dist/{review-candidates-34S6R3DJ.js → review-candidates-BJPY54JI.js} +2 -2
  53. package/dist/{routing-HWGNYIF3.js → routing-PZNFU3OV.js} +2 -2
  54. package/dist/schedule-tool-C3CE6GJG.js +2 -0
  55. package/dist/scheduler-PJMGEJMR.js +2 -0
  56. package/dist/{seat-OQZY3CW7.js → seat-4OONQEDH.js} +2 -2
  57. package/dist/{select-BBTWL7FN.js → select-BR3NBXW7.js} +2 -2
  58. package/dist/{set-enabled-OC3YT4D4.js → set-enabled-Z3NKON2M.js} +2 -2
  59. package/dist/{surface-usage-O5L4KLGS.js → surface-usage-CH3SHO77.js} +2 -2
  60. package/dist/{tool-R36FDI6E.js → tool-DWMZ5OWI.js} +2 -2
  61. package/dist/{tool-P4AHNZ5O.js → tool-SV55IZS3.js} +2 -2
  62. package/dist/wiki-EWEJOKP7.js +2 -0
  63. package/package.json +1 -1
  64. package/dist/chunk-3CHAPGUX.js.map +0 -1
  65. package/dist/chunk-DWZYVYZS.js.map +0 -1
  66. package/dist/chunk-TNR7AI4H.js.map +0 -1
  67. package/dist/config-mutator-UPLM7KGO.js +0 -2
  68. package/dist/processes-TXEWMXXJ.js +0 -2
  69. package/dist/program-QKXRASTV.js.map +0 -1
  70. package/dist/schedule-tool-JLIS2GQU.js +0 -2
  71. package/dist/scheduler-F6NRVZ7W.js +0 -2
  72. package/dist/wiki-5E4AGLKY.js +0 -2
  73. /package/dist/{App-BSGDYHRD.js.map → App-LC34QQPN.js.map} +0 -0
  74. /package/dist/{ChatApp-K57DBCDT.js.map → ChatApp-FB72AK7M.js.map} +0 -0
  75. /package/dist/{agent-6MTUM5DR.js.map → agent-OZ4XFAD4.js.map} +0 -0
  76. /package/dist/{chunk-ECCPLASB.js.map → chunk-26UFDYRZ.js.map} +0 -0
  77. /package/dist/{chunk-HQWMWSSE.js.map → chunk-3GN255MT.js.map} +0 -0
  78. /package/dist/{chunk-7QDAGGOD.js.map → chunk-3SEFVZA7.js.map} +0 -0
  79. /package/dist/{chunk-XVDASTUX.js.map → chunk-64UK5VG4.js.map} +0 -0
  80. /package/dist/{chunk-N4HFUAPN.js.map → chunk-A5DFX47N.js.map} +0 -0
  81. /package/dist/{chunk-HOXHUFZB.js.map → chunk-BEJCSZOQ.js.map} +0 -0
  82. /package/dist/{chunk-BFY4D4RH.js.map → chunk-BTTQZWYB.js.map} +0 -0
  83. /package/dist/{chunk-I6HCIQCQ.js.map → chunk-ISIJAZGO.js.map} +0 -0
  84. /package/dist/{chunk-C3VCIEZS.js.map → chunk-JF5UGNMG.js.map} +0 -0
  85. /package/dist/{chunk-2FLVU2QW.js.map → chunk-JLCYQZRT.js.map} +0 -0
  86. /package/dist/{chunk-MZQ5PCLA.js.map → chunk-LCWE2GHC.js.map} +0 -0
  87. /package/dist/{chunk-7K5SJJUI.js.map → chunk-LS6KXRXY.js.map} +0 -0
  88. /package/dist/{chunk-KIXDJEGA.js.map → chunk-MBVRADNG.js.map} +0 -0
  89. /package/dist/{chunk-X2F3AVGR.js.map → chunk-N2OMSKIQ.js.map} +0 -0
  90. /package/dist/{chunk-EUXF2GJY.js.map → chunk-QYFF2WJ2.js.map} +0 -0
  91. /package/dist/{chunk-BOENB3IK.js.map → chunk-TA2BYYNZ.js.map} +0 -0
  92. /package/dist/{chunk-OAA7TNB6.js.map → chunk-TGN7K7VG.js.map} +0 -0
  93. /package/dist/{chunk-7ADEEHZQ.js.map → chunk-TS7JDPOY.js.map} +0 -0
  94. /package/dist/{chunk-BYD5B3P3.js.map → chunk-UVMCAZL7.js.map} +0 -0
  95. /package/dist/{chunk-7OEFPYQJ.js.map → chunk-UWH7NTGV.js.map} +0 -0
  96. /package/dist/{client-UKLOVDZB.js.map → client-IPZRCNE7.js.map} +0 -0
  97. /package/dist/{config-WUDWHRT6.js.map → config-HZTKLB6A.js.map} +0 -0
  98. /package/dist/{config-mutator-UPLM7KGO.js.map → config-mutator-6S4X6WMU.js.map} +0 -0
  99. /package/dist/{doctor-COAIIKLV.js.map → doctor-BTHIQN7F.js.map} +0 -0
  100. /package/dist/{processes-TXEWMXXJ.js.map → processes-MMAVAZAC.js.map} +0 -0
  101. /package/dist/{promote-B7FGHUFA.js.map → promote-RDXNGZKX.js.map} +0 -0
  102. /package/dist/{query-ZSVAGGSM.js.map → query-OGMNU45Y.js.map} +0 -0
  103. /package/dist/{registry-4DWWYWDR.js.map → registry-LKIOKDIG.js.map} +0 -0
  104. /package/dist/{request-planner-DSXXT75B.js.map → request-planner-EP6QJAK5.js.map} +0 -0
  105. /package/dist/{review-candidates-34S6R3DJ.js.map → review-candidates-BJPY54JI.js.map} +0 -0
  106. /package/dist/{routing-HWGNYIF3.js.map → routing-PZNFU3OV.js.map} +0 -0
  107. /package/dist/{schedule-tool-JLIS2GQU.js.map → schedule-tool-C3CE6GJG.js.map} +0 -0
  108. /package/dist/{scheduler-F6NRVZ7W.js.map → scheduler-PJMGEJMR.js.map} +0 -0
  109. /package/dist/{seat-OQZY3CW7.js.map → seat-4OONQEDH.js.map} +0 -0
  110. /package/dist/{select-BBTWL7FN.js.map → select-BR3NBXW7.js.map} +0 -0
  111. /package/dist/{set-enabled-OC3YT4D4.js.map → set-enabled-Z3NKON2M.js.map} +0 -0
  112. /package/dist/{surface-usage-O5L4KLGS.js.map → surface-usage-CH3SHO77.js.map} +0 -0
  113. /package/dist/{tool-R36FDI6E.js.map → tool-DWMZ5OWI.js.map} +0 -0
  114. /package/dist/{tool-P4AHNZ5O.js.map → tool-SV55IZS3.js.map} +0 -0
  115. /package/dist/{wiki-5E4AGLKY.js.map → wiki-EWEJOKP7.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as Se}from"./chunk-GTJIKXDB.js";import{a as w}from"./chunk-DWZYVYZS.js";import{q as Wt}from"./chunk-S2GAEH2F.js";import{t as jt,u as Vt}from"./chunk-7QDAGGOD.js";import{d as Ot,e as Nt}from"./chunk-AQASR6KR.js";import{c as xe,e as B,f as U,h as Ft}from"./chunk-XIYWXCNU.js";import{A as ke,b as be,v as At,x as Q,y as we}from"./chunk-KIXDJEGA.js";import{a as Pt,b as Lt,d as Mt}from"./chunk-Y4CYQV7G.js";import{a as It,b as Rt}from"./chunk-SHEUCITK.js";import{g as _t,h as Ct,i as Dt,k as Et,l as Tt}from"./chunk-BOENB3IK.js";import{q as $t}from"./chunk-HQWMWSSE.js";import{a as St,b as vt}from"./chunk-I6HCIQCQ.js";import{X as ye,ca as wt,da as kt,ga as xt,m as Z,n as gt,o as mt,p as Tr,u as yt,v as bt,w as Mr}from"./chunk-54VYZE7A.js";import{a as ht,i as Lr}from"./chunk-PN6XHTG5.js";import{a as he,h as Pr}from"./chunk-BRK6M6LA.js";import{existsSync as Or,readdirSync as Nr,readFileSync as jr,statSync as Vr}from"fs";import{resolve as Wr}from"path";function Bt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],c=a.filter(g=>n-g.at<=r),l=a.filter(g=>n-g.at>r&&n-g.at<=r*2),u=c.filter(g=>g.status==="failed").length,d=a.filter(g=>g.status==="paused").length,p=a.length?Math.max(...a.map(g=>g.at)):null,f=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:f,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var ee=new Map;function ra(t,e=1e3){if(!Or(t))return[];let n=Nr(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=Wr(t,s);return{path:o,mtime:Vr(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of ee.keys())i.has(s)||ee.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=ee.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let c=Fr(s,o);ee.set(s,{mtime:o,summary:c}),c&&r.push(c)}return r}function Fr(t,e){try{let n=jr(t,"utf-8").split(`
1
+ import{a as Se}from"./chunk-GTJIKXDB.js";import{a as w}from"./chunk-3SZ4CU6G.js";import{q as Wt}from"./chunk-S2GAEH2F.js";import{t as jt,u as Vt}from"./chunk-3SEFVZA7.js";import{d as Ot,e as Nt}from"./chunk-AQASR6KR.js";import{c as xe,e as B,f as U,h as Ft}from"./chunk-XIYWXCNU.js";import{A as ke,b as be,v as At,x as Q,y as we}from"./chunk-MBVRADNG.js";import{a as Pt,b as Lt,d as Mt}from"./chunk-Y4CYQV7G.js";import{a as It,b as Rt}from"./chunk-SHEUCITK.js";import{g as _t,h as Ct,i as Dt,k as Et,l as Tt}from"./chunk-TA2BYYNZ.js";import{q as $t}from"./chunk-3GN255MT.js";import{a as St,b as vt}from"./chunk-ISIJAZGO.js";import{X as ye,ca as wt,da as kt,ga as xt,m as Z,n as gt,o as mt,p as Tr,u as yt,v as bt,w as Mr}from"./chunk-XSVGD64O.js";import{a as ht,i as Lr}from"./chunk-RJ7DASOU.js";import{a as he,h as Pr}from"./chunk-BRK6M6LA.js";import{existsSync as Or,readdirSync as Nr,readFileSync as jr,statSync as Vr}from"fs";import{resolve as Wr}from"path";function Bt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],c=a.filter(g=>n-g.at<=r),l=a.filter(g=>n-g.at>r&&n-g.at<=r*2),u=c.filter(g=>g.status==="failed").length,d=a.filter(g=>g.status==="paused").length,p=a.length?Math.max(...a.map(g=>g.at)):null,f=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:f,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var ee=new Map;function ra(t,e=1e3){if(!Or(t))return[];let n=Nr(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=Wr(t,s);return{path:o,mtime:Vr(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of ee.keys())i.has(s)||ee.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=ee.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let c=Fr(s,o);ee.set(s,{mtime:o,summary:c}),c&&r.push(c)}return r}function Fr(t,e){try{let n=jr(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let i=JSON.parse(n[0]),r=i.run?.workflowId;if(!r)return null;let s=i.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),c=a.status??a.run?.status;if(c){s=c;break}}return{workflowId:r,status:s,at:e}}catch{return null}}var Br={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},Ur=(t,e,n)=>{try{return $t(t,e,n)}catch{return null}},Ut=864e5;function aa(t){let e=t.now??Date.now(),n={...Br,...t.thresholds},i=t.nextFire??Ur,r=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",u=c.map(f=>({at:Date.parse(f.startedAt),status:f.status})),d=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?ve(a.nextRun)??ve(i(a.schedule,new Date(e),l)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:Xr(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:c.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:zt(u),sampledRuns:c.length,flags:[],attention:null};p.flags=Ht(p,u,a.schedule,l,null,e,n,i),r.push(qt(p))}let s=new Map(Bt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let c=o.get(a.workflowId);c?c.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(I=>I.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},u=a.state||"active",d=u==="active",p=(o.get(a.id)??[]).slice().sort((I,me)=>me.at-I.at),f=p.map(I=>({at:I.at,status:qr(I.status)})),g=f[0],h=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",D=typeof l.timezone=="string"?l.timezone:"UTC",N={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,k.text),trigger:h?{schedule:$(y,k.text),timezone:D}:{event:$(typeof l.event=="string"?l.event:"",k.text),filters:Gr(l.filter,a)},agent:Kr(a),enabled:d,state:u,nextRunAt:h&&d&&y?ve(i(y,new Date(e),D)):null,lastRun:g?{at:new Date(g.at).toISOString(),status:g.status}:null,lastSuccessAt:(()=>{let I=f.find(me=>me.status==="success");return I?new Date(I.at).toISOString():null})(),consecutiveFailures:zt(f),sampledRuns:p.length,flags:[],attention:null},Y=Date.parse(a.updated||a.created||"");N.flags=h?Ht(N,f,y,D,Number.isFinite(Y)?Y:null,e,n,i):zr(N,s.get(a.id)?.state==="dormant",Number.isFinite(Y)?Y:null,e,n),r.push(qt(N))}return r.sort(Hr).slice(0,k.routines)}function zt(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function Ht(t,e,n,i,r,s,o,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=Gt(l,r,s,o);return p&&c.push(p),c}if(t.consecutiveFailures>=o.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let u=new Date(l),d=null;for(let p=0;p<o.missedFires&&(d=a(n,u,i),!!d);p++)u=d;return d&&s>d.getTime()+o.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${o.missedFires} scheduled fires missed`}),c}function zr(t,e,n,i,r){let s=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Gt(o,n,i,r);return a&&s.push(a),s}return t.consecutiveFailures>=r.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function Gt(t,e,n,i){let r=Math.max(t??0,e??0);return r&&n-r<i.disabledDays*Ut?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/Ut)} days`:"Disabled and never ran"}}function qt(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var Kt={critical:0,warning:1,info:2};function Hr(t,e){let n=t.attention?Kt[t.attention]:3,i=e.attention?Kt[e.attention]:3;return n-i||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function qr(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Kr(t){if(t.ownerAgent)return $(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),k.text):null}function Gr(t,e){let n=[],i=e?.project;if(i&&n.push($(`project=${i}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,s]of Object.entries(t)){let o=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];o.length&&n.push($(`${r}=${o.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function ve(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Xr(t,e){return t===void 0?void 0:$(t,e)}import{existsSync as re,readdirSync as fi,readFileSync as gi}from"fs";import{resolve as E}from"path";import{randomBytes as Yt}from"crypto";import{existsSync as Yr,mkdirSync as Zr,readdirSync as Qr,readFileSync as ei,renameSync as Zt,unlinkSync as ti,writeFileSync as ni}from"fs";import{resolve as Qt}from"path";function Xt(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Jr=t=>t.trim().split(`
3
3
  `).pop()?.slice(0,300)||"no output";async function Jt(t,e,n,i=Se){let r=await i(t.bin,[...Xt(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Jr(r.stderr||r.stdout)}`}}async function ua(t,e,n,i,r=Se){return(await r(t.bin,[...Xt(t),"--read-only","media","download","--chat",e,"--id",n,"--output",i],{timeoutMs:12e4})).code===0}var ri=2e3,ii=t=>Jt(t.wacli,t.to,t.text);function $e(t){return Qt(t,".agentx","whatsapp-triage","drafts")}var si=t=>/^[a-z0-9-]{8,64}$/.test(t),te=(t,e)=>Qt($e(t),`${e}.json`);function en(t,e){Zr($e(t),{recursive:!0});let n=te(t,e.id),i=`${n}.${process.pid}.tmp`;ni(i,JSON.stringify(e,null,2)+`
4
4
  `,{mode:384}),Zt(i,n)}function ha(t,e,n=Date.now()){let i=e.text.trim().slice(0,ri);if(!i)throw new Error("empty draft");let r={...e,text:i,id:`${n.toString(36)}-${Yt(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return en(t,r),r}function ne(t,e){if(!si(e))return null;try{return JSON.parse(ei(te(t,e),"utf-8"))}catch{return null}}function tn(t,e){let n=$e(t);return Yr(n)?Qr(n).filter(i=>i.endsWith(".json")).map(i=>ne(t,i.slice(0,-5))).filter(i=>!!i&&(!e||i.status===e)).sort((i,r)=>i.created_at.localeCompare(r.created_at)):[]}async function nn(t,e,n,i={}){let r=ne(t,e);if(!r||r.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${te(t,e)}.${process.pid}.${Yt(3).toString("hex")}.claim`;try{Zt(te(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let o={...r,decided_by:i.by??"operator",decided_at:new Date(i.now??Date.now()).toISOString()};if(n==="no")o.status="rejected";else{let a=await(i.send??ii)(r).catch(c=>({ok:!1,error:String(c?.message??c)}));a.ok?o.status="sent":(o.status="failed",o.error=a.error)}en(t,o);try{ti(s)}catch{}return o.status==="failed"?{ok:!1,error:o.error??"send failed"}:{ok:!0,draft:o}}import{mkdirSync as oi,readFileSync as ai,renameSync as ci,writeFileSync as li}from"fs";import{resolve as ui}from"path";function rn(t){return ui(xe(t),"_state.json")}function R(t){try{let e=JSON.parse(ai(rn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function z(t,e){oi(xe(t),{recursive:!0});let n=rn(t),i=`${n}.${process.pid}.tmp`;li(i,JSON.stringify(e,null,2)+`
@@ -477,4 +477,4 @@ Document the arguments, commands, or files the skill expects. Example:
477
477
  claude-code ${ft(t)} --arg value
478
478
  \`\`\`
479
479
  `}xt();var _r={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Cr(t){return{..._r,...t??{},regions:{...t?.regions??{}},buffer:{..._r.buffer,...t?.buffer??{}}}}function hu(t){try{return Cr(kt(t).screen)}catch{return Cr(void 0)}}var ea=/^[a-z][\w-]*$/,Dr=["window","screen","menubar","notifications"];function J(t,e,n,i){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${i}`);return r}var ge=(t,e)=>J(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Er(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function yu(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=ge(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=ge(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=ge(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=J(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=J(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[s,o]of Object.entries(e.regions)){if(!ea.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);o===null?delete r[s]:r[s]=Er(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,s={...n.buffer??{}};"enabled"in r&&(s.enabled=!!r.enabled),"seconds"in r&&(s.seconds=J(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(s.fps=J(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(s.maxPixels=ge(r.maxPixels,"buffer.maxPixels")),"region"in r&&(s.region=String(r.region).trim()),n.buffer=s}let i=n.buffer?.region;if(i!==void 0&&!Dr.includes(i)&&!n.regions?.[i])try{Er(i)}catch{throw new Error(`buffer.region "${i}" is not a region \u2014 use ${[...Dr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Bt as a,ra as b,Je as c,Cs as d,Ds as e,Nc as f,jc as g,Vc as h,Gn as i,Fc as j,Uc as k,T as l,Xn as m,k as n,aa as o,ua as p,ii as q,ha as r,nn as s,R as t,xa as u,Sa as v,cn as w,_a as x,pn as y,Ba as z,gn as A,cr as B,ml as C,hl as D,Sl as E,yo as F,vl as G,za as H,Ha as I,qa as J,Ka as K,Ga as L,Xa as M,Ya as N,Za as O,ac as P,Te as Q,cc as R,lc as S,H as T,q as U,vo as V,Tl as W,Pl as X,Ll as Y,Ml as Z,tt as _,Ol as $,Me as aa,Oe as ba,le as ca,Xi as da,Yi as ea,gc as fa,je as ga,Ve as ha,Zi as ia,Qi as ja,Ln as ka,jn as la,mc as ma,ns as na,hc as oa,us as pa,fs as qa,We as ra,ms as sa,Vn as ta,P as ua,yr as va,br as wa,wr as xa,Bl as ya,To as za,xr as Aa,Sr as Ba,Ql as Ca,eu as Da,Go as Ea,tu as Fa,$r as Ga,ue as Ha,_c as Ia,Hn as Ja,Fe as Ka,Ge as La,Mc as Ma,su as Na,ou as Oa,au as Pa,cu as Qa,lu as Ra,uu as Sa,du as Ta,pu as Ua,fu as Va,_r as Wa,Cr as Xa,hu as Ya,Dr as Za,yu as _a};
480
- //# sourceMappingURL=chunk-X2F3AVGR.js.map
480
+ //# sourceMappingURL=chunk-N2OMSKIQ.js.map
@@ -1,7 +1,7 @@
1
- import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{da as S,ga as L}from"./chunk-54VYZE7A.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as T,constants as H,existsSync as y,readFileSync as b,readdirSync as $,statSync as X}from"fs";import{join as E,resolve as m}from"path";import{homedir as B}from"os";import{createRequire as F}from"module";import{execFile as M}from"child_process";var q=(t,n)=>new Promise(e=>{try{M(t,n,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),N="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(t.run??q)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:N}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:N}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(t={}){let n=[];await Z(n),U(n);let e=K(n);return e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&te(n,e),e&&oe(n,e),e&&await G(n,e),e&&V(n,e),t.running!==!1&&e&&await ie(n,e),{checks:n,summary:W(n)}}var ke=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await J({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
1
+ import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{da as S,ga as L}from"./chunk-XSVGD64O.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as T,constants as H,existsSync as y,readFileSync as b,readdirSync as $,statSync as X}from"fs";import{join as E,resolve as m}from"path";import{homedir as B}from"os";import{createRequire as F}from"module";import{execFile as M}from"child_process";var q=(t,n)=>new Promise(e=>{try{M(t,n,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),N="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(t.run??q)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:N}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:N}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(t={}){let n=[];await Z(n),U(n);let e=K(n);return e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&te(n,e),e&&oe(n,e),e&&await G(n,e),e&&V(n,e),t.running!==!1&&e&&await ie(n,e),{checks:n,summary:W(n)}}var ke=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await J({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
2
2
  `):se(n),process.exit(e.errors>0?1:0)});async function G(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function V(t,n,e=process.platform,i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}}){let s=n.reminders;if(!s?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let r=s.command||"remindctl",a=r.includes("/")?i(r)?r:null:x(r,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${r} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Z(t){let n=R(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return h(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
3
3
  `)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let l;try{l=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{F(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function U(t){if(process.platform!=="darwin")return;let n=E(B(),"Library/LaunchAgents"),e=[];try{e=$(n).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(E(n,s),"utf-8")),a=x("ffmpeg",r,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${r}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function K(t){let n=m(process.cwd(),"agentx.json");if(!y(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function Q(t,n){let e=new Set;if(C(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=m(process.cwd(),".env"),s={};if(y(i))for(let l of b(i,"utf-8").split(/\r?\n/)){let u=l.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);u&&(s[u[1]]=u[2])}let r=[],a=[];for(let l of e){let u=process.env[l]??s[l];u===void 0?r.push(l):(!u.trim()||/^["']?\s*["']?$/.test(u))&&a.push(l)}r.length===0&&a.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&t.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),a.length>0&&t.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)C(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))C(e,n)}function Y(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{X(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
4
4
  `),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function ee(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(n.agents||{})){if(!r.workspace)continue;let a=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let l of["settings.json","settings.local.json"]){let u=m(a,".claude",l);if(!y(u))continue;let w;try{w=JSON.parse(b(u,"utf-8"))}catch(d){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${d.message}`});continue}let k=w.env||{};for(let[d,p]of Object.entries(k)){if(typeof p!="string")continue;let g=p.match(e);g&&i.push({severity:"fail",agent:s,msg:`${l} env.${d} contains unexpanded ${[...new Set(g)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let o=k.PATH;if(typeof o=="string"){let d=o.split(":").filter(Boolean);d.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)t.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function te(t,n){let e=n.webhooks??[],i=[],s=m(process.cwd(),n.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let o of $(s))o.endsWith(".json")&&!o.startsWith("_")&&!o.endsWith(".disabled.json")&&r.add(o.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let o of e){if(!o.enabled||!a.has(o.source))continue;!(o.triggers&&Object.keys(o.triggers).length>0)&&!o.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${o.id}" (${o.source} -> ${o.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let o of e)if(!(!o.enabled||!o.triggers)){for(let[c,d]of Object.entries(o.triggers))r.size>0&&!r.has(d)&&i.push({severity:"fail",title:`webhook "${o.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});o.defaultWorkflow&&r.size>0&&!r.has(o.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${o.id}".defaultWorkflow -> "${o.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let o of $(s))if(!(!o.endsWith(".json")||o.startsWith("_")||o.endsWith(".disabled.json")))try{let c=JSON.parse(b(m(s,o),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${c.id??o}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(o=>o.name));for(let o of e)!o.enabled||!o.node||l.has(o.node)||i.push({severity:"fail",title:`webhook "${o.id}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let o of e){if(!o.enabled)continue;let c=`${o.source}:${o.agentId}`,d=u.get(c);d?i.push({severity:"warn",title:`webhook entries "${d}" and "${o.id}" both enabled for ${o.source} -> ${o.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(c,o.id)}let w=new Set(Object.keys(n.agents??{}));for(let o of n.channels?.gitlab?.agentMappings??[])if(o?.agentId){if(o.node){l.has(o.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${o.agentId}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(o.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${o.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[o,c]of Object.entries(n.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||i.push({severity:"fail",title:`telegram account "${o}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${o}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let k=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[o,c]of Object.entries(n.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let g of d){let A=`${g.kind}::${g.label}`;p.has(A)&&i.push({severity:"warn",title:`agents.${o}.integrations: duplicate (${g.kind}, ${g.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(A),k.has(g.kind)||i.push({severity:"warn",title:`agents.${o}.integrations: unknown kind "${g.kind}" on integration "${g.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let D=g.credentials||{};for(let[_,v]of Object.entries(D))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${o}.integrations[${g.kind}/${g.label}].${_} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)t.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}function ne(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function ie(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(r),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=ne(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function oe(t,n){let e=Object.entries(n.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
5
5
  `)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=m(r.workspace,".codegraph","codegraph.db");y(a)?t.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function W(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function se(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,s]of n){console.log(f.bold(" "+i));for(let r of s){let a=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
6
6
  `))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=W(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,J as b,ke as c,G as d,V as e,ne as f};
7
- //# sourceMappingURL=chunk-EUXF2GJY.js.map
7
+ //# sourceMappingURL=chunk-QYFF2WJ2.js.map
@@ -1,4 +1,4 @@
1
- import{a as c}from"./chunk-QIJLFPWE.js";import{createRequire as N}from"module";import{mkdirSync as L}from"fs";import{dirname as l,resolve as R}from"path";function d(t){let a=String(t?.message??t),s=process.versions.modules,e=`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${s}).`;return/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(a)?`${a} ${e}`:`${a} ${e}`}function m(t=!1){if(u)return u;try{return u=A("better-sqlite3"),u}catch(a){return t||console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${d(a)}`),null}}function U(t={}){if(t.disabled)return null;if(T)return T;let a=R(process.cwd(),t.path??".agentx/db.sqlite"),s=m(t.quiet);if(!s)return null;try{L(l(a),{recursive:!0});let r=new s(a);return r.pragma("journal_mode = WAL"),r.pragma("synchronous = NORMAL"),r.pragma("foreign_keys = ON"),g(r),T=r,T}catch(r){return t.quiet||console.error(`[storage/sqlite] openDb failed at ${a}: ${d(r)}`),null}}function g(t){t.exec(`
1
+ import{a as c}from"./chunk-QIJLFPWE.js";import{createRequire as N}from"module";import{mkdirSync as L}from"fs";import{dirname as R,resolve as l}from"path";function d(t){let a=String(t?.message??t),s=process.versions.modules,e=`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${s}).`;return/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(a)?`${a} ${e}`:`${a} ${e}`}function m(t=!1){if(o)return o;try{return o=A("better-sqlite3"),o}catch(a){return t||console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${d(a)}`),null}}function U(t={}){if(t.disabled)return null;if(T)return T;let a=l(process.cwd(),t.path??".agentx/db.sqlite"),s=m(t.quiet);if(!s)return null;try{L(R(a),{recursive:!0});let r=new s(a);return r.pragma("journal_mode = WAL"),r.pragma("synchronous = NORMAL"),r.pragma("foreign_keys = ON"),p(r),T=r,T}catch(r){return t.quiet||console.error(`[storage/sqlite] openDb failed at ${a}: ${d(r)}`),null}}function p(t){t.exec(`
2
2
  CREATE TABLE IF NOT EXISTS schema_version (
3
3
  v INTEGER PRIMARY KEY
4
4
  );
@@ -169,7 +169,7 @@ import{a as c}from"./chunk-QIJLFPWE.js";import{createRequire as N}from"module";i
169
169
  `},{v:13,sql:`
170
170
  ALTER TABLE task_traces ADD COLUMN jev_arm TEXT;
171
171
  CREATE INDEX idx_task_traces_jev_arm ON task_traces(jev_arm, started_at);
172
- `}],r=t.transaction(e=>{t.exec(e.sql),t.prepare("INSERT INTO schema_version (v) VALUES (?)").run(e.v)});for(let e of s)e.v>a&&r(e);o(t,"task_traces",p),o(t,"task_traces",D),o(t,"task_traces",_),o(t,"task_history",_)}function f(t,a,s){let r=Date.now(),n=t.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'").get().n<s,E=null;return n||(E=t.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'").get().n+1),t.prepare(`
172
+ `}],r=t.transaction(e=>{t.exec(e.sql),t.prepare("INSERT INTO schema_version (v) VALUES (?)").run(e.v)});for(let e of s)e.v>a&&r(e);u(t,"task_traces",g),u(t,"task_traces",D),u(t,"task_traces",_),u(t,"task_history",_),t.exec("CREATE INDEX IF NOT EXISTS idx_traces_person_started ON task_traces(person, started_at) WHERE person IS NOT NULL")}function f(t,a,s){let r=Date.now(),n=t.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'").get().n<s,E=null;return n||(E=t.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'").get().n+1),t.prepare(`
173
173
  INSERT INTO task_queue (id, conversation_id, agent_id, summary, status, position, created_at, started_at)
174
174
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
175
175
  `).run(a.id,a.conversationId,a.agentId,a.summary,n?"active":"queued",E,r,n?r:null),{id:a.id,status:n?"active":"queued",position:E}}function C(t,a,s="done"){let r=Date.now();t.prepare(`
@@ -183,5 +183,5 @@ import{a as c}from"./chunk-QIJLFPWE.js";import{createRequire as N}from"module";i
183
183
  `).all(),E=t.prepare("UPDATE task_queue SET position = ? WHERE id = ?");for(let i=0;i<n.length;i++)E.run(i+1,n[i].id)}}function h(t,a){let s=t.prepare("SELECT * FROM task_queue WHERE id = ?").get(a);return s?{id:s.id,conversationId:s.conversation_id,agentId:s.agent_id,summary:s.summary,status:s.status,position:s.position,createdAt:s.created_at,startedAt:s.started_at,finishedAt:s.finished_at}:null}function y(t,a,s=20){return t.prepare(`
184
184
  SELECT * FROM task_queue WHERE conversation_id = ?
185
185
  ORDER BY created_at DESC LIMIT ?
186
- `).all(a,s).map(e=>({id:e.id,conversationId:e.conversation_id,agentId:e.agent_id,summary:e.summary,status:e.status,position:e.position,createdAt:e.created_at,startedAt:e.started_at,finishedAt:e.finished_at}))}function b(t,a){let s=Date.now()-a*24*60*60*1e3,r=new Date(s).toISOString(),e=t.prepare("DELETE FROM task_history WHERE started_at < ?").run(r).changes??0,n=t.prepare("DELETE FROM rotations WHERE rotated_at < ?").run(r).changes??0,E=t.prepare("DELETE FROM route_traces WHERE at < ?").run(r).changes??0,i=t.prepare("DELETE FROM task_traces WHERE started_at < ?").run(s).changes??0;if(e+n+E+i>0)try{t.pragma("incremental_vacuum")}catch{}return{taskHistory:e,rotations:n,routeTraces:E,taskTraces:i}}function o(t,a,s){let r=new Set(t.prepare(`PRAGMA table_info(${a})`).all().map(e=>e.name));for(let[e,n]of s)if(!r.has(e))try{t.exec(`ALTER TABLE ${a} ADD COLUMN ${e} ${n}`)}catch(E){if(!/duplicate column name/i.test(String(E?.message)))throw E}}var A,T,u,p,D,_,O=c(()=>{"use strict";A=N(import.meta.url);p=[["resume_origin","TEXT"],["resume_attempt","INTEGER NOT NULL DEFAULT 0"],["resumed_from","TEXT"],["resume_decision","TEXT"],["resume_reason","TEXT"]],D=[["num_turns","INTEGER"],["injected_context","TEXT"]],_=[["person","TEXT"]]});export{U as a,f as b,C as c,h as d,y as e,b as f,_ as g,o as h,O as i};
187
- //# sourceMappingURL=chunk-PN6XHTG5.js.map
186
+ `).all(a,s).map(e=>({id:e.id,conversationId:e.conversation_id,agentId:e.agent_id,summary:e.summary,status:e.status,position:e.position,createdAt:e.created_at,startedAt:e.started_at,finishedAt:e.finished_at}))}function b(t,a){let s=Date.now()-a*24*60*60*1e3,r=new Date(s).toISOString(),e=t.prepare("DELETE FROM task_history WHERE started_at < ?").run(r).changes??0,n=t.prepare("DELETE FROM rotations WHERE rotated_at < ?").run(r).changes??0,E=t.prepare("DELETE FROM route_traces WHERE at < ?").run(r).changes??0,i=t.prepare("DELETE FROM task_traces WHERE started_at < ?").run(s).changes??0;if(e+n+E+i>0)try{t.pragma("incremental_vacuum")}catch{}return{taskHistory:e,rotations:n,routeTraces:E,taskTraces:i}}function u(t,a,s){let r=new Set(t.prepare(`PRAGMA table_info(${a})`).all().map(e=>e.name));for(let[e,n]of s)if(!r.has(e))try{t.exec(`ALTER TABLE ${a} ADD COLUMN ${e} ${n}`)}catch(E){if(!/duplicate column name/i.test(String(E?.message)))throw E}}var A,T,o,g,D,_,O=c(()=>{"use strict";A=N(import.meta.url);g=[["resume_origin","TEXT"],["resume_attempt","INTEGER NOT NULL DEFAULT 0"],["resumed_from","TEXT"],["resume_decision","TEXT"],["resume_reason","TEXT"]],D=[["num_turns","INTEGER"],["injected_context","TEXT"]],_=[["person","TEXT"]]});export{U as a,f as b,C as c,h as d,y as e,b as f,_ as g,u as h,O as i};
187
+ //# sourceMappingURL=chunk-RJ7DASOU.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage/sqlite.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { createRequire } from \"module\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\n\n// --- SQLite storage layer ---\n//\n// Move 2 of the architectural review (docs/architecture/hexabot-vs-agentx.md).\n// SQLite for the operational tables — task_history, usage, dedup, sessions —\n// where queryable, indexed access has user-visible value (dashboards,\n// retention, analytics). Workflow definitions, wiki, agent-memory, and\n// references stay as files: they're git-diffable, human-readable, and don't\n// need queries.\n//\n// Approach: subscribe to the event bus (src/events/bus.ts) and write to\n// SQLite from the subscribers. Existing JSON writes are not touched —\n// SQLite runs alongside as a parallel pipeline. Once we have a query API\n// the dashboard depends on, we can deprecate the JSON path. Until then,\n// SQLite is observability-grade only.\n//\n// Synchronous API: better-sqlite3 is sync, no callbacks. The daemon's\n// event loop is the single writer; multiple readers (dashboard) use WAL\n// mode for concurrent read while we write.\n\ntype DatabaseConstructor = typeof Database\n\nconst require = createRequire(import.meta.url)\nlet _db: Database.Database | undefined\nlet _Database: DatabaseConstructor | undefined\n\nfunction betterSqlite3Fix(error: any): string {\n const msg = String(error?.message ?? error)\n const abi = process.versions.modules\n const node = process.version\n const hint = `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${node}, modules ${abi}).`\n if (/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(msg)) {\n return `${msg} ${hint}`\n }\n return `${msg} ${hint}`\n}\n\nfunction loadDatabaseCtor(quiet = false): DatabaseConstructor | null {\n if (_Database) return _Database\n try {\n _Database = require(\"better-sqlite3\") as DatabaseConstructor\n return _Database\n } catch (e: any) {\n if (!quiet) {\n console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\nexport interface OpenOptions {\n /** Resolved relative to cwd. Default: .agentx/db.sqlite */\n path?: string\n /** When true, SQLite writes are skipped (used by tests + opt-out). */\n disabled?: boolean\n /** Suppress the open-failure log. For best-effort callers whose whole\n * contract is \"do nothing if unavailable\" — telemetry, mainly. Without\n * this, a native-binding ABI mismatch prints a paragraph of node-gyp\n * advice on EVERY CLI invocation, which is worse than the thing it\n * is warning about. Load-bearing callers must never pass it. */\n quiet?: boolean\n}\n\n/**\n * Open the per-process SQLite database. Idempotent — repeated calls\n * return the same handle. The file is created on first open; the schema\n * is migrated forward to the latest version.\n *\n * Returns null when disabled — every subscriber should check for null\n * before issuing a write so the daemon stays runnable without SQLite if\n * someone's environment can't compile the native binding.\n */\nexport function openDb(opts: OpenOptions = {}): Database.Database | null {\n if (opts.disabled) return null\n if (_db) return _db\n const path = resolve(process.cwd(), opts.path ?? \".agentx/db.sqlite\")\n const Database = loadDatabaseCtor(opts.quiet)\n if (!Database) return null\n try {\n mkdirSync(dirname(path), { recursive: true })\n const db = new Database(path)\n // WAL keeps readers (dashboard) unblocked while the daemon writes.\n // Synchronous=NORMAL is the SQLite-recommended balance for WAL: the\n // db is durable on power-loss, but a crash within the last few ms can\n // lose the most recent commit. For our use (observability), that's fine.\n db.pragma(\"journal_mode = WAL\")\n db.pragma(\"synchronous = NORMAL\")\n db.pragma(\"foreign_keys = ON\")\n runMigrations(db)\n _db = db\n return _db\n } catch (e: any) {\n // Native binding missing, file unwritable, etc. Surface by default — the\n // alternative was a silent no-op, which makes the \"SQLite not opened\"\n // message in the daemon log impossible to debug. `quiet` callers have\n // explicitly opted out because doing nothing is their correct behavior.\n if (!opts.quiet) {\n console.error(`[storage/sqlite] openDb failed at ${path}: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\n/** Close the global handle. Test-only — production never closes. */\nexport function closeDb(): void {\n if (_db) {\n _db.close()\n _db = undefined\n }\n}\n\n/**\n * Per-version schema steps. New tables / columns go in a new migration —\n * never mutate an old one. Run on every open(); each step is idempotent\n * because it CREATE TABLE IF NOT EXISTS. SQLite has no concurrent\n * migration issue here (single writer process).\n */\nfunction runMigrations(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS schema_version (\n v INTEGER PRIMARY KEY\n );\n `)\n const current = (db\n .prepare(\"SELECT MAX(v) AS v FROM schema_version\")\n .get() as { v: number | null }).v ?? 0\n\n const steps: Array<{ v: number; sql: string }> = [\n {\n v: 1,\n sql: `\n CREATE TABLE task_history (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n status TEXT NOT NULL, -- 'ok' | 'error' | 'timeout'\n message_preview TEXT,\n error TEXT,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n started_at TEXT NOT NULL,\n finished_at TEXT NOT NULL\n );\n CREATE INDEX idx_task_history_agent_started\n ON task_history(agent_id, started_at);\n CREATE INDEX idx_task_history_status\n ON task_history(status, started_at);\n `,\n },\n {\n v: 2,\n sql: `\n CREATE TABLE usage_daily (\n agent_id TEXT NOT NULL,\n model TEXT NOT NULL,\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n input_tokens INTEGER DEFAULT 0,\n output_tokens INTEGER DEFAULT 0,\n cache_read_tokens INTEGER DEFAULT 0,\n cache_create_tokens INTEGER DEFAULT 0,\n tasks INTEGER DEFAULT 0,\n PRIMARY KEY (agent_id, model, day)\n );\n CREATE INDEX idx_usage_day ON usage_daily(day);\n `,\n },\n {\n v: 3,\n sql: `\n CREATE TABLE rotations (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n reason TEXT NOT NULL, -- 'stale' | 'tier-2' | 'max-turns'\n last_turn_input_tokens INTEGER,\n rotated_at TEXT NOT NULL\n );\n CREATE INDEX idx_rotations_agent_at\n ON rotations(agent_id, rotated_at);\n `,\n },\n {\n v: 4,\n sql: `\n CREATE TABLE route_traces (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n msg_id TEXT NOT NULL,\n account_id TEXT,\n kind TEXT NOT NULL, -- 'match' | 'drop'\n deciding_stage TEXT,\n agent_id TEXT,\n reason TEXT,\n at TEXT NOT NULL\n );\n CREATE INDEX idx_route_traces_channel_at\n ON route_traces(channel, at);\n `,\n },\n {\n // Move A — tier-2 token buckets on usage_daily. The per-request tier\n // split is decided at record time by TokenTracker (it's a function of\n // the live cumulative input, not the row totals), so we cannot\n // reconstruct it on read. Adding columns is additive and idempotent;\n // existing rows default to 0.\n v: 5,\n sql: `\n ALTER TABLE usage_daily ADD COLUMN tier2_input_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_output_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_read_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_create_tokens INTEGER DEFAULT 0;\n `,\n },\n {\n // task_traces — per-execution observability surface (improvement plan\n // #2). One row per executeTask invocation, keyed by a ULID task_id so\n // it's URL-safe + monotonically sortable. Workflow context columns let\n // pattern queries group runs by workflow (\"agent-managed workflow as\n // the program\" framing); intent_event_id cross-links into the rescue\n // plan's intent ledger so a dispatch decision joins to the execution\n // it produced. Tokens snapshot the final usage at finish time.\n v: 6,\n sql: `\n CREATE TABLE task_traces (\n task_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n workflow_run_id TEXT,\n workflow_id TEXT,\n workflow_node_id TEXT,\n intent_event_id TEXT,\n intent_decided_by TEXT,\n resume_session_id TEXT,\n final_session_id TEXT,\n model TEXT,\n status TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n finished_at INTEGER,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n error TEXT,\n message_preview TEXT\n );\n CREATE INDEX idx_traces_agent_started ON task_traces(agent_id, started_at);\n CREATE INDEX idx_traces_workflow_run ON task_traces(workflow_run_id);\n CREATE INDEX idx_traces_intent_event ON task_traces(intent_event_id);\n CREATE INDEX idx_traces_status_started ON task_traces(status, started_at);\n `,\n },\n {\n // task_trace_steps — append-only step ledger inside one task. Sequence\n // numbers are 0-based and unique per task_id; ON DELETE CASCADE so\n // pruning task_traces removes children atomically. The (input|output)_\n // summary columns are TEXT — callers cap byte-size at the call site,\n // not in the schema, because the right cap depends on the step kind\n // (a tool_use's args vs a tool_result's stdout have very different\n // typical sizes).\n v: 7,\n sql: `\n CREATE TABLE task_trace_steps (\n task_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n name TEXT NOT NULL,\n action TEXT,\n status TEXT,\n input_summary TEXT,\n output_summary TEXT,\n error TEXT,\n ms INTEGER,\n started_at INTEGER NOT NULL,\n PRIMARY KEY (task_id, seq),\n FOREIGN KEY (task_id) REFERENCES task_traces(task_id) ON DELETE CASCADE\n );\n CREATE INDEX idx_trace_steps_name ON task_trace_steps(name, started_at);\n `,\n },\n {\n // task replay support (handoff item #11). Capture the full original\n // user message AND the agent's final response so 'agentx trace replay\n // <taskId> --diff' can show side-by-side without reconstructing from\n // the step ledger. message_preview stays for cheap listing UX (200\n // chars); original_message holds the untruncated input. final_response\n // mirrors the agent's reply text. Both NULLABLE — old rows have NULL\n // and the replay command falls back to the preview gracefully.\n v: 8,\n sql: `\n ALTER TABLE task_traces ADD COLUMN original_message TEXT;\n ALTER TABLE task_traces ADD COLUMN final_response TEXT;\n `,\n },\n {\n // task_queue — persistent chat-initiated work queue (Phase 2).\n // Each row represents a task an agent queued during a /chat turn.\n // status: 'active' = currently running; 'queued' = waiting;\n // 'done' = completed; 'error' = failed.\n // position is 1-based rank among queued rows (null when active/done/error).\n v: 9,\n sql: `\n CREATE TABLE task_queue (\n id TEXT PRIMARY KEY,\n conversation_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n summary TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'queued',\n position INTEGER,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n finished_at INTEGER\n );\n CREATE INDEX idx_task_queue_status ON task_queue(status, created_at);\n CREATE INDEX idx_task_queue_convo ON task_queue(conversation_id, created_at);\n `,\n },\n {\n // guardrail_decisions — audit trail for the destructive-action guard\n // (PRD R7). One row per PreToolUse guard verdict, written by the\n // short-lived `agentx guard check` hook process. `verdict` is the\n // policy's decision (allow|deny|escalate|warn); `effective_action` is\n // what was actually enforced after the mode downgrade (in warn mode a\n // deny is recorded as verdict=deny, effective_action=allow). task_id is\n // a logical link to task_traces when the guard can resolve it (often\n // null — the hook doesn't always know the AgentX task id). `approver`\n // is reserved for Phase 2 escalation (human who approved/denied).\n v: 10,\n sql: `\n CREATE TABLE guardrail_decisions (\n id TEXT PRIMARY KEY,\n ts INTEGER NOT NULL,\n agent_id TEXT,\n task_id TEXT,\n tool TEXT NOT NULL,\n command TEXT,\n resolved_target TEXT,\n matched_rule TEXT,\n verdict TEXT NOT NULL,\n effective_action TEXT NOT NULL,\n mode TEXT,\n severity TEXT,\n approver TEXT,\n ms INTEGER\n );\n CREATE INDEX idx_guardrail_ts ON guardrail_decisions(ts);\n CREATE INDEX idx_guardrail_verdict ON guardrail_decisions(verdict, ts);\n CREATE INDEX idx_guardrail_agent ON guardrail_decisions(agent_id, ts);\n `,\n },\n {\n // Which operator surfaces actually get used. task_history records agent\n // dispatches and says nothing about which of the ~46 CLI commands or 16\n // dashboard pages anyone opens — the two biggest surfaces by count, and\n // the ones the surface-reduction work needs evidence for.\n //\n // Deliberately NOT folded into usage_daily: that table is keyed by\n // (agent_id, model, day) and is about token cost. Surface counts share\n // none of that shape, and mixing them would corrupt cost reporting.\n //\n // Names only — never arguments, paths, or payloads. This counts which\n // door was opened, not what was carried through it.\n v: 11,\n sql: `\n CREATE TABLE surface_usage (\n kind TEXT NOT NULL, -- 'cli' | 'page'\n name TEXT NOT NULL, -- 'guard log' | '/live'\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n count INTEGER NOT NULL DEFAULT 0,\n last_at TEXT,\n PRIMARY KEY (kind, name, day)\n );\n CREATE INDEX idx_surface_day ON surface_usage(day);\n `,\n },\n {\n // Per-turn token accounting that a with/without comparison can trust.\n // task_traces only carried the tier-1 buckets, and tier-2 turns are\n // where 90%+ of prompt tokens land, so most big turns read as zero.\n // `resumed` is explicit rather than inferred from resume_session_id:\n // NULL means \"not recorded\" (older rows), 0 a fresh session.\n v: 12,\n sql: `\n ALTER TABLE task_traces ADD COLUMN tier2_input_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_output_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_read_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_create_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN resumed INTEGER;\n `,\n },\n {\n // Request-gate experiment arm: 'treatment' (asked Jev), 'holdout'\n // (randomly skipped it), or NULL when the gate was not active. The\n // with/without-Jev comparison groups turns on this column.\n v: 13,\n sql: `\n ALTER TABLE task_traces ADD COLUMN jev_arm TEXT;\n CREATE INDEX idx_task_traces_jev_arm ON task_traces(jev_arm, started_at);\n `,\n },\n ]\n\n const txn = db.transaction((step: { v: number; sql: string }) => {\n db.exec(step.sql)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (?)\").run(step.v)\n })\n\n for (const step of steps) {\n if (step.v > current) txn(step)\n }\n\n // Columns added by name, not by version number. Several branches can each\n // claim the next migration number; a database that already recorded that\n // number from another branch would silently skip ours. Checking the\n // table itself makes these columns appear on every database.\n ensureColumns(db, \"task_traces\", RESUME_COLUMNS)\n ensureColumns(db, \"task_traces\", LESSON_IMPACT_COLUMNS)\n ensureColumns(db, \"task_traces\", PERSON_COLUMNS)\n ensureColumns(db, \"task_history\", PERSON_COLUMNS)\n}\n\n/** Schema version check for tests. */\nexport function getSchemaVersion(db: Database.Database): number {\n return (db.prepare(\"SELECT MAX(v) AS v FROM schema_version\").get() as { v: number | null }).v ?? 0\n}\n\n// --- task_queue helpers (Phase 2 chat-initiated work queue) ---\n\nexport interface TaskQueueEntry {\n id: string\n conversationId: string\n agentId: string\n summary: string\n status: \"active\" | \"queued\" | \"done\" | \"error\"\n position: number | null\n createdAt: number\n startedAt: number | null\n finishedAt: number | null\n}\n\nexport interface InsertTaskQueueResult {\n id: string\n status: \"active\" | \"queued\"\n position: number | null\n}\n\n/**\n * Insert a new task into the queue. Respects maxConcurrent — if the number\n * of 'active' rows is below the limit the new task is inserted as 'active';\n * otherwise it is 'queued' with a 1-based position.\n */\nexport function insertTaskQueue(\n db: Database.Database,\n entry: { id: string; conversationId: string; agentId: string; summary: string },\n maxConcurrent: number,\n): InsertTaskQueueResult {\n const now = Date.now()\n const activeCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'\")\n .get() as { n: number }).n\n\n const isActive = activeCount < maxConcurrent\n let position: number | null = null\n if (!isActive) {\n const queuedCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'\")\n .get() as { n: number }).n\n position = queuedCount + 1\n }\n\n db.prepare(`\n INSERT INTO task_queue (id, conversation_id, agent_id, summary, status, position, created_at, started_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n entry.id,\n entry.conversationId,\n entry.agentId,\n entry.summary,\n isActive ? \"active\" : \"queued\",\n position,\n now,\n isActive ? now : null,\n )\n\n return { id: entry.id, status: isActive ? \"active\" : \"queued\", position }\n}\n\n/**\n * Mark a task done/error and promote the next queued task (if any) to active.\n */\nexport function completeTaskQueue(\n db: Database.Database,\n id: string,\n status: \"done\" | \"error\" = \"done\",\n): void {\n const now = Date.now()\n db.prepare(`\n UPDATE task_queue SET status = ?, finished_at = ?, position = NULL WHERE id = ?\n `).run(status, now, id)\n\n // Promote oldest queued task to active\n const next = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1\n `).get() as { id: string } | undefined\n if (next) {\n db.prepare(`\n UPDATE task_queue SET status = 'active', position = NULL, started_at = ? WHERE id = ?\n `).run(now, next.id)\n // Resequence remaining queued positions\n const remaining = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC\n `).all() as Array<{ id: string }>\n const upd = db.prepare(\"UPDATE task_queue SET position = ? WHERE id = ?\")\n for (let i = 0; i < remaining.length; i++) {\n upd.run(i + 1, remaining[i].id)\n }\n }\n}\n\n/** Look up a single task_queue row. */\nexport function getTaskQueue(\n db: Database.Database,\n id: string,\n): TaskQueueEntry | null {\n const row = db.prepare(\"SELECT * FROM task_queue WHERE id = ?\").get(id) as Record<string, unknown> | undefined\n if (!row) return null\n return {\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }\n}\n\n/** List task_queue rows for a conversation, newest first. */\nexport function listTaskQueueByConversation(\n db: Database.Database,\n conversationId: string,\n limit = 20,\n): TaskQueueEntry[] {\n const rows = db.prepare(`\n SELECT * FROM task_queue WHERE conversation_id = ?\n ORDER BY created_at DESC LIMIT ?\n `).all(conversationId, limit) as Array<Record<string, unknown>>\n return rows.map((row) => ({\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }))\n}\n\nexport interface PruneResult {\n taskHistory: number\n rotations: number\n routeTraces: number\n taskTraces: number\n}\n\n/**\n * Drop rows older than `retentionDays` from the operational tables that grow\n * unbounded over time. `usage_daily` is bounded by (agent, model, day) and\n * doesn't need pruning; the caller decides whether to keep aggregates beyond\n * the retention window.\n *\n * Mirrors the file-based `pruneTaskHistory` sweep that runs at daemon\n * startup. Cheap — three indexed deletes plus an incremental_vacuum.\n */\nexport function pruneSqliteTables(\n db: Database.Database,\n retentionDays: number,\n): PruneResult {\n const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1000\n const cutoffIso = new Date(cutoffMs).toISOString()\n\n const taskHistory = (db\n .prepare(`DELETE FROM task_history WHERE started_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const rotations = (db\n .prepare(`DELETE FROM rotations WHERE rotated_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const routeTraces = (db\n .prepare(`DELETE FROM route_traces WHERE at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n // task_traces uses ms-epoch INTEGERs (not ISO strings) on started_at.\n // task_trace_steps cascades automatically via ON DELETE CASCADE.\n const taskTraces = (db\n .prepare(`DELETE FROM task_traces WHERE started_at < ?`)\n .run(cutoffMs).changes ?? 0) as number\n\n // Reclaim the freelist pages so the file shrinks. WAL writes still\n // checkpoint independently.\n if (taskHistory + rotations + routeTraces + taskTraces > 0) {\n try { db.pragma(\"incremental_vacuum\") } catch { /* best-effort */ }\n }\n\n return { taskHistory, rotations, routeTraces, taskTraces }\n}\n\n/** Resume after restart (#103): how to re-enter a run (JSON), its attempt\n * number, the cut-off run it continues, and the boot decision made for it. */\nconst RESUME_COLUMNS: Array<[string, string]> = [\n [\"resume_origin\", \"TEXT\"],\n [\"resume_attempt\", \"INTEGER NOT NULL DEFAULT 0\"],\n [\"resumed_from\", \"TEXT\"],\n [\"resume_decision\", \"TEXT\"],\n [\"resume_reason\", \"TEXT\"],\n]\n\n/** Lesson impact (#98): the memory facts and procedures injected into a turn,\n * as JSON {memory: ids, procedures: ids, wiki: bool}, plus the runtime's turn\n * count. `agentx trace lessons` compares a repeated task before and after\n * each lesson on these columns. */\nconst LESSON_IMPACT_COLUMNS: Array<[string, string]> = [\n [\"num_turns\", \"INTEGER\"],\n [\"injected_context\", \"TEXT\"],\n]\n\n/** People (#384): the id of the known person who started the run. NULL for\n * an unknown sender, for turns software starts, and on older rows. */\nexport const PERSON_COLUMNS: Array<[string, string]> = [[\"person\", \"TEXT\"]]\n\n/** Add any of `columns` the table lacks. Idempotent. */\nexport function ensureColumns(db: Database.Database, table: string, columns: Array<[string, string]>): void {\n const have = new Set((db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).map((c) => c.name))\n for (const [name, type] of columns) {\n if (have.has(name)) continue\n try {\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${type}`)\n } catch (e: any) {\n // Two processes starting on one database: the slower one read the\n // table before the faster one added the column. Already there is fine.\n if (!/duplicate column name/i.test(String(e?.message))) throw e\n }\n }\n}\n"],"mappings":"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,EAAE,SAAW,EACvBG,EAAejC,EAClB,QAAQ,uCAAuC,EAC/C,IAAI8B,CAAS,EAAE,SAAW,EAGvBI,EAAclC,EACjB,QAAQ,8CAA8C,EACtD,IAAI6B,CAAQ,EAAE,SAAW,EAI5B,GAAIE,EAAcC,EAAYC,EAAcC,EAAa,EACvD,GAAI,CAAElC,EAAG,OAAO,oBAAoB,CAAE,MAAE,CAA0B,CAGpE,MAAO,CAAE,YAAA+B,EAAa,UAAAC,EAAW,YAAAC,EAAa,WAAAC,CAAW,CAC3D,CA0BO,SAAS5B,EAAcN,EAAuBmC,EAAeC,EAAwC,CAC1G,IAAMC,EAAO,IAAI,IAAKrC,EAAG,QAAQ,qBAAqBmC,IAAQ,EAAE,IAAI,EAA8B,IAAKG,GAAMA,EAAE,IAAI,CAAC,EACpH,OAAW,CAACC,EAAMC,CAAI,IAAKJ,EACzB,GAAI,CAAAC,EAAK,IAAIE,CAAI,EACjB,GAAI,CACFvC,EAAG,KAAK,eAAemC,gBAAoBI,KAAQC,GAAM,CAC3D,OAAS9C,EAAP,CAGA,GAAI,CAAC,yBAAyB,KAAK,OAAOA,GAAG,OAAO,CAAC,EAAG,MAAMA,CAChE,CAEJ,CA/oBA,IA0BMD,EACFI,EACAL,EAilBEe,EAYAC,EAOOC,EAhoBbgC,EAAAC,EAAA,kBA0BMjD,EAAUZ,EAAc,YAAY,GAAG,EAmlBvC0B,EAA0C,CAC9C,CAAC,gBAAiB,MAAM,EACxB,CAAC,iBAAkB,4BAA4B,EAC/C,CAAC,eAAgB,MAAM,EACvB,CAAC,kBAAmB,MAAM,EAC1B,CAAC,gBAAiB,MAAM,CAC1B,EAMMC,EAAiD,CACrD,CAAC,YAAa,SAAS,EACvB,CAAC,mBAAoB,MAAM,CAC7B,EAIaC,EAA0C,CAAC,CAAC,SAAU,MAAM,CAAC","names":["createRequire","mkdirSync","dirname","resolve","betterSqlite3Fix","error","msg","abi","hint","loadDatabaseCtor","quiet","_Database","require","e","openDb","opts","_db","path","Database","db","runMigrations","current","steps","txn","step","ensureColumns","RESUME_COLUMNS","LESSON_IMPACT_COLUMNS","PERSON_COLUMNS","insertTaskQueue","entry","maxConcurrent","now","isActive","position","completeTaskQueue","id","status","next","remaining","upd","getTaskQueue","row","listTaskQueueByConversation","conversationId","limit","pruneSqliteTables","retentionDays","cutoffMs","cutoffIso","taskHistory","rotations","routeTraces","taskTraces","table","columns","have","c","name","type","init_sqlite","__esmMin"]}
1
+ {"version":3,"sources":["../src/storage/sqlite.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { createRequire } from \"module\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\n\n// --- SQLite storage layer ---\n//\n// Move 2 of the architectural review (docs/architecture/hexabot-vs-agentx.md).\n// SQLite for the operational tables — task_history, usage, dedup, sessions —\n// where queryable, indexed access has user-visible value (dashboards,\n// retention, analytics). Workflow definitions, wiki, agent-memory, and\n// references stay as files: they're git-diffable, human-readable, and don't\n// need queries.\n//\n// Approach: subscribe to the event bus (src/events/bus.ts) and write to\n// SQLite from the subscribers. Existing JSON writes are not touched —\n// SQLite runs alongside as a parallel pipeline. Once we have a query API\n// the dashboard depends on, we can deprecate the JSON path. Until then,\n// SQLite is observability-grade only.\n//\n// Synchronous API: better-sqlite3 is sync, no callbacks. The daemon's\n// event loop is the single writer; multiple readers (dashboard) use WAL\n// mode for concurrent read while we write.\n\ntype DatabaseConstructor = typeof Database\n\nconst require = createRequire(import.meta.url)\nlet _db: Database.Database | undefined\nlet _Database: DatabaseConstructor | undefined\n\nfunction betterSqlite3Fix(error: any): string {\n const msg = String(error?.message ?? error)\n const abi = process.versions.modules\n const node = process.version\n const hint = `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${node}, modules ${abi}).`\n if (/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(msg)) {\n return `${msg} ${hint}`\n }\n return `${msg} ${hint}`\n}\n\nfunction loadDatabaseCtor(quiet = false): DatabaseConstructor | null {\n if (_Database) return _Database\n try {\n _Database = require(\"better-sqlite3\") as DatabaseConstructor\n return _Database\n } catch (e: any) {\n if (!quiet) {\n console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\nexport interface OpenOptions {\n /** Resolved relative to cwd. Default: .agentx/db.sqlite */\n path?: string\n /** When true, SQLite writes are skipped (used by tests + opt-out). */\n disabled?: boolean\n /** Suppress the open-failure log. For best-effort callers whose whole\n * contract is \"do nothing if unavailable\" — telemetry, mainly. Without\n * this, a native-binding ABI mismatch prints a paragraph of node-gyp\n * advice on EVERY CLI invocation, which is worse than the thing it\n * is warning about. Load-bearing callers must never pass it. */\n quiet?: boolean\n}\n\n/**\n * Open the per-process SQLite database. Idempotent — repeated calls\n * return the same handle. The file is created on first open; the schema\n * is migrated forward to the latest version.\n *\n * Returns null when disabled — every subscriber should check for null\n * before issuing a write so the daemon stays runnable without SQLite if\n * someone's environment can't compile the native binding.\n */\nexport function openDb(opts: OpenOptions = {}): Database.Database | null {\n if (opts.disabled) return null\n if (_db) return _db\n const path = resolve(process.cwd(), opts.path ?? \".agentx/db.sqlite\")\n const Database = loadDatabaseCtor(opts.quiet)\n if (!Database) return null\n try {\n mkdirSync(dirname(path), { recursive: true })\n const db = new Database(path)\n // WAL keeps readers (dashboard) unblocked while the daemon writes.\n // Synchronous=NORMAL is the SQLite-recommended balance for WAL: the\n // db is durable on power-loss, but a crash within the last few ms can\n // lose the most recent commit. For our use (observability), that's fine.\n db.pragma(\"journal_mode = WAL\")\n db.pragma(\"synchronous = NORMAL\")\n db.pragma(\"foreign_keys = ON\")\n runMigrations(db)\n _db = db\n return _db\n } catch (e: any) {\n // Native binding missing, file unwritable, etc. Surface by default — the\n // alternative was a silent no-op, which makes the \"SQLite not opened\"\n // message in the daemon log impossible to debug. `quiet` callers have\n // explicitly opted out because doing nothing is their correct behavior.\n if (!opts.quiet) {\n console.error(`[storage/sqlite] openDb failed at ${path}: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\n/** Close the global handle. Test-only — production never closes. */\nexport function closeDb(): void {\n if (_db) {\n _db.close()\n _db = undefined\n }\n}\n\n/**\n * Per-version schema steps. New tables / columns go in a new migration —\n * never mutate an old one. Run on every open(); each step is idempotent\n * because it CREATE TABLE IF NOT EXISTS. SQLite has no concurrent\n * migration issue here (single writer process).\n */\nfunction runMigrations(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS schema_version (\n v INTEGER PRIMARY KEY\n );\n `)\n const current = (db\n .prepare(\"SELECT MAX(v) AS v FROM schema_version\")\n .get() as { v: number | null }).v ?? 0\n\n const steps: Array<{ v: number; sql: string }> = [\n {\n v: 1,\n sql: `\n CREATE TABLE task_history (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n status TEXT NOT NULL, -- 'ok' | 'error' | 'timeout'\n message_preview TEXT,\n error TEXT,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n started_at TEXT NOT NULL,\n finished_at TEXT NOT NULL\n );\n CREATE INDEX idx_task_history_agent_started\n ON task_history(agent_id, started_at);\n CREATE INDEX idx_task_history_status\n ON task_history(status, started_at);\n `,\n },\n {\n v: 2,\n sql: `\n CREATE TABLE usage_daily (\n agent_id TEXT NOT NULL,\n model TEXT NOT NULL,\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n input_tokens INTEGER DEFAULT 0,\n output_tokens INTEGER DEFAULT 0,\n cache_read_tokens INTEGER DEFAULT 0,\n cache_create_tokens INTEGER DEFAULT 0,\n tasks INTEGER DEFAULT 0,\n PRIMARY KEY (agent_id, model, day)\n );\n CREATE INDEX idx_usage_day ON usage_daily(day);\n `,\n },\n {\n v: 3,\n sql: `\n CREATE TABLE rotations (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n reason TEXT NOT NULL, -- 'stale' | 'tier-2' | 'max-turns'\n last_turn_input_tokens INTEGER,\n rotated_at TEXT NOT NULL\n );\n CREATE INDEX idx_rotations_agent_at\n ON rotations(agent_id, rotated_at);\n `,\n },\n {\n v: 4,\n sql: `\n CREATE TABLE route_traces (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n msg_id TEXT NOT NULL,\n account_id TEXT,\n kind TEXT NOT NULL, -- 'match' | 'drop'\n deciding_stage TEXT,\n agent_id TEXT,\n reason TEXT,\n at TEXT NOT NULL\n );\n CREATE INDEX idx_route_traces_channel_at\n ON route_traces(channel, at);\n `,\n },\n {\n // Move A — tier-2 token buckets on usage_daily. The per-request tier\n // split is decided at record time by TokenTracker (it's a function of\n // the live cumulative input, not the row totals), so we cannot\n // reconstruct it on read. Adding columns is additive and idempotent;\n // existing rows default to 0.\n v: 5,\n sql: `\n ALTER TABLE usage_daily ADD COLUMN tier2_input_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_output_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_read_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_create_tokens INTEGER DEFAULT 0;\n `,\n },\n {\n // task_traces — per-execution observability surface (improvement plan\n // #2). One row per executeTask invocation, keyed by a ULID task_id so\n // it's URL-safe + monotonically sortable. Workflow context columns let\n // pattern queries group runs by workflow (\"agent-managed workflow as\n // the program\" framing); intent_event_id cross-links into the rescue\n // plan's intent ledger so a dispatch decision joins to the execution\n // it produced. Tokens snapshot the final usage at finish time.\n v: 6,\n sql: `\n CREATE TABLE task_traces (\n task_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n workflow_run_id TEXT,\n workflow_id TEXT,\n workflow_node_id TEXT,\n intent_event_id TEXT,\n intent_decided_by TEXT,\n resume_session_id TEXT,\n final_session_id TEXT,\n model TEXT,\n status TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n finished_at INTEGER,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n error TEXT,\n message_preview TEXT\n );\n CREATE INDEX idx_traces_agent_started ON task_traces(agent_id, started_at);\n CREATE INDEX idx_traces_workflow_run ON task_traces(workflow_run_id);\n CREATE INDEX idx_traces_intent_event ON task_traces(intent_event_id);\n CREATE INDEX idx_traces_status_started ON task_traces(status, started_at);\n `,\n },\n {\n // task_trace_steps — append-only step ledger inside one task. Sequence\n // numbers are 0-based and unique per task_id; ON DELETE CASCADE so\n // pruning task_traces removes children atomically. The (input|output)_\n // summary columns are TEXT — callers cap byte-size at the call site,\n // not in the schema, because the right cap depends on the step kind\n // (a tool_use's args vs a tool_result's stdout have very different\n // typical sizes).\n v: 7,\n sql: `\n CREATE TABLE task_trace_steps (\n task_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n name TEXT NOT NULL,\n action TEXT,\n status TEXT,\n input_summary TEXT,\n output_summary TEXT,\n error TEXT,\n ms INTEGER,\n started_at INTEGER NOT NULL,\n PRIMARY KEY (task_id, seq),\n FOREIGN KEY (task_id) REFERENCES task_traces(task_id) ON DELETE CASCADE\n );\n CREATE INDEX idx_trace_steps_name ON task_trace_steps(name, started_at);\n `,\n },\n {\n // task replay support (handoff item #11). Capture the full original\n // user message AND the agent's final response so 'agentx trace replay\n // <taskId> --diff' can show side-by-side without reconstructing from\n // the step ledger. message_preview stays for cheap listing UX (200\n // chars); original_message holds the untruncated input. final_response\n // mirrors the agent's reply text. Both NULLABLE — old rows have NULL\n // and the replay command falls back to the preview gracefully.\n v: 8,\n sql: `\n ALTER TABLE task_traces ADD COLUMN original_message TEXT;\n ALTER TABLE task_traces ADD COLUMN final_response TEXT;\n `,\n },\n {\n // task_queue — persistent chat-initiated work queue (Phase 2).\n // Each row represents a task an agent queued during a /chat turn.\n // status: 'active' = currently running; 'queued' = waiting;\n // 'done' = completed; 'error' = failed.\n // position is 1-based rank among queued rows (null when active/done/error).\n v: 9,\n sql: `\n CREATE TABLE task_queue (\n id TEXT PRIMARY KEY,\n conversation_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n summary TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'queued',\n position INTEGER,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n finished_at INTEGER\n );\n CREATE INDEX idx_task_queue_status ON task_queue(status, created_at);\n CREATE INDEX idx_task_queue_convo ON task_queue(conversation_id, created_at);\n `,\n },\n {\n // guardrail_decisions — audit trail for the destructive-action guard\n // (PRD R7). One row per PreToolUse guard verdict, written by the\n // short-lived `agentx guard check` hook process. `verdict` is the\n // policy's decision (allow|deny|escalate|warn); `effective_action` is\n // what was actually enforced after the mode downgrade (in warn mode a\n // deny is recorded as verdict=deny, effective_action=allow). task_id is\n // a logical link to task_traces when the guard can resolve it (often\n // null — the hook doesn't always know the AgentX task id). `approver`\n // is reserved for Phase 2 escalation (human who approved/denied).\n v: 10,\n sql: `\n CREATE TABLE guardrail_decisions (\n id TEXT PRIMARY KEY,\n ts INTEGER NOT NULL,\n agent_id TEXT,\n task_id TEXT,\n tool TEXT NOT NULL,\n command TEXT,\n resolved_target TEXT,\n matched_rule TEXT,\n verdict TEXT NOT NULL,\n effective_action TEXT NOT NULL,\n mode TEXT,\n severity TEXT,\n approver TEXT,\n ms INTEGER\n );\n CREATE INDEX idx_guardrail_ts ON guardrail_decisions(ts);\n CREATE INDEX idx_guardrail_verdict ON guardrail_decisions(verdict, ts);\n CREATE INDEX idx_guardrail_agent ON guardrail_decisions(agent_id, ts);\n `,\n },\n {\n // Which operator surfaces actually get used. task_history records agent\n // dispatches and says nothing about which of the ~46 CLI commands or 16\n // dashboard pages anyone opens — the two biggest surfaces by count, and\n // the ones the surface-reduction work needs evidence for.\n //\n // Deliberately NOT folded into usage_daily: that table is keyed by\n // (agent_id, model, day) and is about token cost. Surface counts share\n // none of that shape, and mixing them would corrupt cost reporting.\n //\n // Names only — never arguments, paths, or payloads. This counts which\n // door was opened, not what was carried through it.\n v: 11,\n sql: `\n CREATE TABLE surface_usage (\n kind TEXT NOT NULL, -- 'cli' | 'page'\n name TEXT NOT NULL, -- 'guard log' | '/live'\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n count INTEGER NOT NULL DEFAULT 0,\n last_at TEXT,\n PRIMARY KEY (kind, name, day)\n );\n CREATE INDEX idx_surface_day ON surface_usage(day);\n `,\n },\n {\n // Per-turn token accounting that a with/without comparison can trust.\n // task_traces only carried the tier-1 buckets, and tier-2 turns are\n // where 90%+ of prompt tokens land, so most big turns read as zero.\n // `resumed` is explicit rather than inferred from resume_session_id:\n // NULL means \"not recorded\" (older rows), 0 a fresh session.\n v: 12,\n sql: `\n ALTER TABLE task_traces ADD COLUMN tier2_input_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_output_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_read_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_create_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN resumed INTEGER;\n `,\n },\n {\n // Request-gate experiment arm: 'treatment' (asked Jev), 'holdout'\n // (randomly skipped it), or NULL when the gate was not active. The\n // with/without-Jev comparison groups turns on this column.\n v: 13,\n sql: `\n ALTER TABLE task_traces ADD COLUMN jev_arm TEXT;\n CREATE INDEX idx_task_traces_jev_arm ON task_traces(jev_arm, started_at);\n `,\n },\n ]\n\n const txn = db.transaction((step: { v: number; sql: string }) => {\n db.exec(step.sql)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (?)\").run(step.v)\n })\n\n for (const step of steps) {\n if (step.v > current) txn(step)\n }\n\n // Columns added by name, not by version number. Several branches can each\n // claim the next migration number; a database that already recorded that\n // number from another branch would silently skip ours. Checking the\n // table itself makes these columns appear on every database.\n ensureColumns(db, \"task_traces\", RESUME_COLUMNS)\n ensureColumns(db, \"task_traces\", LESSON_IMPACT_COLUMNS)\n ensureColumns(db, \"task_traces\", PERSON_COLUMNS)\n ensureColumns(db, \"task_history\", PERSON_COLUMNS)\n // A person's latest turns, read by the member page every 30 s (#448).\n // Without it that read walks every run on record. Partial: most runs\n // carry no person, and those rows stay out of the index.\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_traces_person_started ON task_traces(person, started_at) WHERE person IS NOT NULL\")\n}\n\n/** Schema version check for tests. */\nexport function getSchemaVersion(db: Database.Database): number {\n return (db.prepare(\"SELECT MAX(v) AS v FROM schema_version\").get() as { v: number | null }).v ?? 0\n}\n\n// --- task_queue helpers (Phase 2 chat-initiated work queue) ---\n\nexport interface TaskQueueEntry {\n id: string\n conversationId: string\n agentId: string\n summary: string\n status: \"active\" | \"queued\" | \"done\" | \"error\"\n position: number | null\n createdAt: number\n startedAt: number | null\n finishedAt: number | null\n}\n\nexport interface InsertTaskQueueResult {\n id: string\n status: \"active\" | \"queued\"\n position: number | null\n}\n\n/**\n * Insert a new task into the queue. Respects maxConcurrent — if the number\n * of 'active' rows is below the limit the new task is inserted as 'active';\n * otherwise it is 'queued' with a 1-based position.\n */\nexport function insertTaskQueue(\n db: Database.Database,\n entry: { id: string; conversationId: string; agentId: string; summary: string },\n maxConcurrent: number,\n): InsertTaskQueueResult {\n const now = Date.now()\n const activeCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'\")\n .get() as { n: number }).n\n\n const isActive = activeCount < maxConcurrent\n let position: number | null = null\n if (!isActive) {\n const queuedCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'\")\n .get() as { n: number }).n\n position = queuedCount + 1\n }\n\n db.prepare(`\n INSERT INTO task_queue (id, conversation_id, agent_id, summary, status, position, created_at, started_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n entry.id,\n entry.conversationId,\n entry.agentId,\n entry.summary,\n isActive ? \"active\" : \"queued\",\n position,\n now,\n isActive ? now : null,\n )\n\n return { id: entry.id, status: isActive ? \"active\" : \"queued\", position }\n}\n\n/**\n * Mark a task done/error and promote the next queued task (if any) to active.\n */\nexport function completeTaskQueue(\n db: Database.Database,\n id: string,\n status: \"done\" | \"error\" = \"done\",\n): void {\n const now = Date.now()\n db.prepare(`\n UPDATE task_queue SET status = ?, finished_at = ?, position = NULL WHERE id = ?\n `).run(status, now, id)\n\n // Promote oldest queued task to active\n const next = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1\n `).get() as { id: string } | undefined\n if (next) {\n db.prepare(`\n UPDATE task_queue SET status = 'active', position = NULL, started_at = ? WHERE id = ?\n `).run(now, next.id)\n // Resequence remaining queued positions\n const remaining = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC\n `).all() as Array<{ id: string }>\n const upd = db.prepare(\"UPDATE task_queue SET position = ? WHERE id = ?\")\n for (let i = 0; i < remaining.length; i++) {\n upd.run(i + 1, remaining[i].id)\n }\n }\n}\n\n/** Look up a single task_queue row. */\nexport function getTaskQueue(\n db: Database.Database,\n id: string,\n): TaskQueueEntry | null {\n const row = db.prepare(\"SELECT * FROM task_queue WHERE id = ?\").get(id) as Record<string, unknown> | undefined\n if (!row) return null\n return {\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }\n}\n\n/** List task_queue rows for a conversation, newest first. */\nexport function listTaskQueueByConversation(\n db: Database.Database,\n conversationId: string,\n limit = 20,\n): TaskQueueEntry[] {\n const rows = db.prepare(`\n SELECT * FROM task_queue WHERE conversation_id = ?\n ORDER BY created_at DESC LIMIT ?\n `).all(conversationId, limit) as Array<Record<string, unknown>>\n return rows.map((row) => ({\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }))\n}\n\nexport interface PruneResult {\n taskHistory: number\n rotations: number\n routeTraces: number\n taskTraces: number\n}\n\n/**\n * Drop rows older than `retentionDays` from the operational tables that grow\n * unbounded over time. `usage_daily` is bounded by (agent, model, day) and\n * doesn't need pruning; the caller decides whether to keep aggregates beyond\n * the retention window.\n *\n * Mirrors the file-based `pruneTaskHistory` sweep that runs at daemon\n * startup. Cheap — three indexed deletes plus an incremental_vacuum.\n */\nexport function pruneSqliteTables(\n db: Database.Database,\n retentionDays: number,\n): PruneResult {\n const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1000\n const cutoffIso = new Date(cutoffMs).toISOString()\n\n const taskHistory = (db\n .prepare(`DELETE FROM task_history WHERE started_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const rotations = (db\n .prepare(`DELETE FROM rotations WHERE rotated_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const routeTraces = (db\n .prepare(`DELETE FROM route_traces WHERE at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n // task_traces uses ms-epoch INTEGERs (not ISO strings) on started_at.\n // task_trace_steps cascades automatically via ON DELETE CASCADE.\n const taskTraces = (db\n .prepare(`DELETE FROM task_traces WHERE started_at < ?`)\n .run(cutoffMs).changes ?? 0) as number\n\n // Reclaim the freelist pages so the file shrinks. WAL writes still\n // checkpoint independently.\n if (taskHistory + rotations + routeTraces + taskTraces > 0) {\n try { db.pragma(\"incremental_vacuum\") } catch { /* best-effort */ }\n }\n\n return { taskHistory, rotations, routeTraces, taskTraces }\n}\n\n/** Resume after restart (#103): how to re-enter a run (JSON), its attempt\n * number, the cut-off run it continues, and the boot decision made for it. */\nconst RESUME_COLUMNS: Array<[string, string]> = [\n [\"resume_origin\", \"TEXT\"],\n [\"resume_attempt\", \"INTEGER NOT NULL DEFAULT 0\"],\n [\"resumed_from\", \"TEXT\"],\n [\"resume_decision\", \"TEXT\"],\n [\"resume_reason\", \"TEXT\"],\n]\n\n/** Lesson impact (#98): the memory facts and procedures injected into a turn,\n * as JSON {memory: ids, procedures: ids, wiki: bool}, plus the runtime's turn\n * count. `agentx trace lessons` compares a repeated task before and after\n * each lesson on these columns. */\nconst LESSON_IMPACT_COLUMNS: Array<[string, string]> = [\n [\"num_turns\", \"INTEGER\"],\n [\"injected_context\", \"TEXT\"],\n]\n\n/** People (#384): the id of the known person who started the run. NULL for\n * an unknown sender, for turns software starts, and on older rows. */\nexport const PERSON_COLUMNS: Array<[string, string]> = [[\"person\", \"TEXT\"]]\n\n/** Add any of `columns` the table lacks. Idempotent. */\nexport function ensureColumns(db: Database.Database, table: string, columns: Array<[string, string]>): void {\n const have = new Set((db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).map((c) => c.name))\n for (const [name, type] of columns) {\n if (have.has(name)) continue\n try {\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${type}`)\n } catch (e: any) {\n // Two processes starting on one database: the slower one read the\n // table before the faster one added the column. Already there is fine.\n if (!/duplicate column name/i.test(String(e?.message))) throw e\n }\n }\n}\n"],"mappings":"wCACA,OAAS,iBAAAA,MAAqB,SAC9B,OAAqB,aAAAC,MAAiB,KACtC,OAAS,WAAAC,EAAS,WAAAC,MAAe,OA2BjC,SAASC,EAAiBC,EAAoB,CAC5C,IAAMC,EAAM,OAAOD,GAAO,SAAWA,CAAK,EACpCE,EAAM,QAAQ,SAAS,QAEvBC,EAAO,4EADA,QAAQ,oBACqFD,MAC1G,MAAI,uFAAuF,KAAKD,CAAG,EAC1F,GAAGA,KAAOE,IAEZ,GAAGF,KAAOE,GACnB,CAEA,SAASC,EAAiBC,EAAQ,GAAmC,CAC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W,CAC3D,CA0BO,SAAS5B,EAAcN,EAAuBmC,EAAeC,EAAwC,CAC1G,IAAMC,EAAO,IAAI,IAAKrC,EAAG,QAAQ,qBAAqBmC,IAAQ,EAAE,IAAI,EAA8B,IAAKG,GAAMA,EAAE,IAAI,CAAC,EACpH,OAAW,CAACC,EAAMC,CAAI,IAAKJ,EACzB,GAAI,CAAAC,EAAK,IAAIE,CAAI,EACjB,GAAI,CACFvC,EAAG,KAAK,eAAemC,gBAAoBI,KAAQC,GAAM,CAC3D,OAAS9C,EAAP,CAGA,GAAI,CAAC,yBAAyB,KAAK,OAAOA,GAAG,OAAO,CAAC,EAAG,MAAMA,CAChE,CAEJ,CAnpBA,IA0BMD,EACFI,EACAL,EAqlBEe,EAYAC,EAOOC,EApoBbgC,EAAAC,EAAA,kBA0BMjD,EAAUZ,EAAc,YAAY,GAAG,EAulBvC0B,EAA0C,CAC9C,CAAC,gBAAiB,MAAM,EACxB,CAAC,iBAAkB,4BAA4B,EAC/C,CAAC,eAAgB,MAAM,EACvB,CAAC,kBAAmB,MAAM,EAC1B,CAAC,gBAAiB,MAAM,CAC1B,EAMMC,EAAiD,CACrD,CAAC,YAAa,SAAS,EACvB,CAAC,mBAAoB,MAAM,CAC7B,EAIaC,EAA0C,CAAC,CAAC,SAAU,MAAM,CAAC","names":["createRequire","mkdirSync","dirname","resolve","betterSqlite3Fix","error","msg","abi","hint","loadDatabaseCtor","quiet","_Database","require","e","openDb","opts","_db","path","Database","db","runMigrations","current","steps","txn","step","ensureColumns","RESUME_COLUMNS","LESSON_IMPACT_COLUMNS","PERSON_COLUMNS","insertTaskQueue","entry","maxConcurrent","now","isActive","position","completeTaskQueue","id","status","next","remaining","upd","getTaskQueue","row","listTaskQueueByConversation","conversationId","limit","pruneSqliteTables","retentionDays","cutoffMs","cutoffIso","taskHistory","rotations","routeTraces","taskTraces","table","columns","have","c","name","type","init_sqlite","__esmMin"]}