agentix-cli 0.209.1 → 0.210.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 (163) hide show
  1. package/dist/{App-IIRTJERA.js → App-EMCBJ5NE.js} +2 -2
  2. package/dist/{ChatApp-6KKF4LEH.js → ChatApp-HIHZEUKS.js} +2 -2
  3. package/dist/{absorb-eval-TUJ5NT6O.js → absorb-eval-7CCHO4KZ.js} +2 -2
  4. package/dist/{adapter-OEPJK3RA.js → adapter-J6YO4FLT.js} +2 -2
  5. package/dist/{agent-BOU3OKAD.js → agent-AETIDS4G.js} +2 -2
  6. package/dist/{board-dashboard-FSQBTYYV.js → board-dashboard-OAAO3ZKR.js} +4 -4
  7. package/dist/{board-dashboard-FSQBTYYV.js.map → board-dashboard-OAAO3ZKR.js.map} +1 -1
  8. package/dist/{chunk-R6O45GIS.js → chunk-426L6XZP.js} +2 -2
  9. package/dist/{chunk-44CTJ3Q7.js → chunk-4CGAIVLW.js} +2 -2
  10. package/dist/{chunk-76H4PAOZ.js → chunk-4GS2I57L.js} +2 -2
  11. package/dist/{chunk-D2FURI7U.js → chunk-5GHYIU5L.js} +2 -2
  12. package/dist/{chunk-DBODYTBR.js → chunk-5UXCARLO.js} +2 -2
  13. package/dist/{chunk-PLIG3TGT.js → chunk-6FCD7K6G.js} +2 -2
  14. package/dist/{chunk-TQSU3X3J.js → chunk-6L3K7Y7E.js} +2 -2
  15. package/dist/{chunk-LS6COERI.js → chunk-6X2K2VSD.js} +2 -2
  16. package/dist/{chunk-YXJV4ACW.js → chunk-CXLAXYZG.js} +278 -278
  17. package/dist/chunk-CXLAXYZG.js.map +1 -0
  18. package/dist/{chunk-ROLSAEXB.js → chunk-D55REZL3.js} +2 -2
  19. package/dist/{chunk-LCVBPN2T.js → chunk-DNQEK2KS.js} +102 -113
  20. package/dist/chunk-DNQEK2KS.js.map +1 -0
  21. package/dist/{chunk-PL5CJYNG.js → chunk-EP3XCCZ3.js} +2 -2
  22. package/dist/{chunk-3S7ZOYP7.js → chunk-F3DCWMTS.js} +2 -2
  23. package/dist/{chunk-MM7CVLQ4.js → chunk-GCR3KWCV.js} +2 -2
  24. package/dist/{chunk-7YKVNEQ6.js → chunk-GMP2IB4E.js} +2 -2
  25. package/dist/{chunk-G72NZCOM.js → chunk-H22TBFXT.js} +2 -2
  26. package/dist/{chunk-SXCRQMNL.js → chunk-KI2M5LXX.js} +2 -2
  27. package/dist/chunk-KWWBDLE6.js +13 -0
  28. package/dist/chunk-KWWBDLE6.js.map +1 -0
  29. package/dist/chunk-LIY5CHUV.js +4 -0
  30. package/dist/chunk-LIY5CHUV.js.map +1 -0
  31. package/dist/{chunk-OCKOQ3M2.js → chunk-N2DOU7A5.js} +3 -3
  32. package/dist/chunk-NWY4OF4X.js +133 -0
  33. package/dist/chunk-NWY4OF4X.js.map +1 -0
  34. package/dist/{chunk-YOIZOUSY.js → chunk-PK2KOR6H.js} +2 -2
  35. package/dist/{chunk-PB6WBFNR.js → chunk-PTDPY5YN.js} +2 -2
  36. package/dist/{chunk-EKQND7TT.js → chunk-RTYBNDHE.js} +2 -2
  37. package/dist/{chunk-T2P6QX4W.js → chunk-TARMAPO6.js} +2 -2
  38. package/dist/{chunk-UXOKTRDR.js → chunk-TAUJUPJN.js} +2 -2
  39. package/dist/{chunk-2YKGPMLS.js → chunk-TNIN3DPC.js} +2 -2
  40. package/dist/{chunk-KPYBNLA2.js → chunk-TPGQIJOK.js} +2 -2
  41. package/dist/{chunk-ZLYZBZ6P.js → chunk-UEYKYTJD.js} +2 -2
  42. package/dist/{chunk-EDWOZ54V.js → chunk-UQMNYIGT.js} +2 -2
  43. package/dist/{chunk-EDWOZ54V.js.map → chunk-UQMNYIGT.js.map} +1 -1
  44. package/dist/{chunk-7PNHK54L.js → chunk-W3DLKUOV.js} +2 -2
  45. package/dist/{chunk-6WZV65AF.js → chunk-WSHOJMQG.js} +2 -2
  46. package/dist/cli.js +1 -1
  47. package/dist/client-XITH4RAT.js +2 -0
  48. package/dist/{config-LLC2SVQY.js → config-YYD7E5BT.js} +2 -2
  49. package/dist/config-mutate-F23A3UAU.js +2 -0
  50. package/dist/config-mutator-XHSEEKWW.js +2 -0
  51. package/dist/{contributions-PJ56BN7H.js → contributions-R2BJWBI7.js} +2 -2
  52. package/dist/decision-approvals-NJS2ARAF.js +2 -0
  53. package/dist/{doctor-GUOMJIP2.js → doctor-2GK4QVSK.js} +2 -2
  54. package/dist/{follow-up-tool-WJDVBIKK.js → follow-up-tool-FT5JYKSI.js} +2 -2
  55. package/dist/hub-QBJH2GAV.js +2 -0
  56. package/dist/index.d.ts +23 -0
  57. package/dist/index.js +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/{org-tool-DSNS2U6J.js → org-tool-BTZF5L74.js} +2 -2
  60. package/dist/owner-decisions-D3MBTX4D.js +2 -0
  61. package/dist/{program-TFUYZJXY.js → program-O5MDSQSU.js} +291 -283
  62. package/dist/program-O5MDSQSU.js.map +1 -0
  63. package/dist/{promote-JFNEREPV.js → promote-JQYV4QKG.js} +2 -2
  64. package/dist/push-bridge-T5HZZRA2.js +1 -1
  65. package/dist/{query-AZV6567L.js → query-RW3BV23C.js} +2 -2
  66. package/dist/{query-settings-NVR6KLT6.js → query-settings-DN6BU3QA.js} +2 -2
  67. package/dist/registry-CQLEJUHN.js +2 -0
  68. package/dist/{request-planner-63YQLEPP.js → request-planner-M4GOEJUD.js} +2 -2
  69. package/dist/{review-candidates-MMCISAK2.js → review-candidates-HZDY5DV3.js} +2 -2
  70. package/dist/routing-IUE6GT6T.js +2 -0
  71. package/dist/schedule-tool-WAXHHKSR.js +2 -0
  72. package/dist/scheduler-PPKHYCMH.js +2 -0
  73. package/dist/{seat-JXZWBSGZ.js → seat-OIVGQP4P.js} +2 -2
  74. package/dist/{select-FSV56KVJ.js → select-TKODF5NC.js} +2 -2
  75. package/dist/self-HICJTWYO.js +2 -0
  76. package/dist/{set-enabled-53DEYHY3.js → set-enabled-B3A2VMDN.js} +2 -2
  77. package/dist/{sprint-tool-PYRQIJKM.js → sprint-tool-N4RLQ3EN.js} +2 -2
  78. package/dist/{tool-O73Q2WWD.js → tool-FQY3IU4B.js} +2 -2
  79. package/dist/{tool-YEH3GUG6.js → tool-FUEAREQB.js} +2 -2
  80. package/dist/{tool-JKDVJJD4.js → tool-SBFQKJ4J.js} +2 -2
  81. package/dist/{tool-4N5XR4XV.js → tool-UL673LK6.js} +2 -2
  82. package/dist/wiki-S6FJAVZ6.js +2 -0
  83. package/dist/wiki-S6FJAVZ6.js.map +1 -0
  84. package/dist/wiki-enrich-UQKBCRS7.js +2 -0
  85. package/dist/wiki-enrich-UQKBCRS7.js.map +1 -0
  86. package/dist/workspace-setup-GTSXWYU4.js +1 -1
  87. package/package.json +1 -1
  88. package/dist/chunk-KT4CZ7GY.js +0 -123
  89. package/dist/chunk-KT4CZ7GY.js.map +0 -1
  90. package/dist/chunk-LCVBPN2T.js.map +0 -1
  91. package/dist/chunk-YXJV4ACW.js.map +0 -1
  92. package/dist/client-MAH6EO3E.js +0 -2
  93. package/dist/config-mutate-2AGZLP25.js +0 -2
  94. package/dist/config-mutator-REAOL7IJ.js +0 -2
  95. package/dist/hub-YOXHLMFE.js +0 -2
  96. package/dist/program-TFUYZJXY.js.map +0 -1
  97. package/dist/registry-FE6NJMV3.js +0 -2
  98. package/dist/routing-MLJJ3R3V.js +0 -2
  99. package/dist/schedule-tool-TVM4RJ35.js +0 -2
  100. package/dist/scheduler-S3KOAAFU.js +0 -2
  101. package/dist/self-CICDOU3F.js +0 -2
  102. package/dist/wiki-GP52MJ6Y.js +0 -2
  103. package/dist/wiki-enrich-M7YDGFIY.js +0 -2
  104. /package/dist/{App-IIRTJERA.js.map → App-EMCBJ5NE.js.map} +0 -0
  105. /package/dist/{ChatApp-6KKF4LEH.js.map → ChatApp-HIHZEUKS.js.map} +0 -0
  106. /package/dist/{absorb-eval-TUJ5NT6O.js.map → absorb-eval-7CCHO4KZ.js.map} +0 -0
  107. /package/dist/{adapter-OEPJK3RA.js.map → adapter-J6YO4FLT.js.map} +0 -0
  108. /package/dist/{agent-BOU3OKAD.js.map → agent-AETIDS4G.js.map} +0 -0
  109. /package/dist/{chunk-R6O45GIS.js.map → chunk-426L6XZP.js.map} +0 -0
  110. /package/dist/{chunk-44CTJ3Q7.js.map → chunk-4CGAIVLW.js.map} +0 -0
  111. /package/dist/{chunk-76H4PAOZ.js.map → chunk-4GS2I57L.js.map} +0 -0
  112. /package/dist/{chunk-D2FURI7U.js.map → chunk-5GHYIU5L.js.map} +0 -0
  113. /package/dist/{chunk-DBODYTBR.js.map → chunk-5UXCARLO.js.map} +0 -0
  114. /package/dist/{chunk-PLIG3TGT.js.map → chunk-6FCD7K6G.js.map} +0 -0
  115. /package/dist/{chunk-TQSU3X3J.js.map → chunk-6L3K7Y7E.js.map} +0 -0
  116. /package/dist/{chunk-LS6COERI.js.map → chunk-6X2K2VSD.js.map} +0 -0
  117. /package/dist/{chunk-ROLSAEXB.js.map → chunk-D55REZL3.js.map} +0 -0
  118. /package/dist/{chunk-PL5CJYNG.js.map → chunk-EP3XCCZ3.js.map} +0 -0
  119. /package/dist/{chunk-3S7ZOYP7.js.map → chunk-F3DCWMTS.js.map} +0 -0
  120. /package/dist/{chunk-MM7CVLQ4.js.map → chunk-GCR3KWCV.js.map} +0 -0
  121. /package/dist/{chunk-7YKVNEQ6.js.map → chunk-GMP2IB4E.js.map} +0 -0
  122. /package/dist/{chunk-G72NZCOM.js.map → chunk-H22TBFXT.js.map} +0 -0
  123. /package/dist/{chunk-SXCRQMNL.js.map → chunk-KI2M5LXX.js.map} +0 -0
  124. /package/dist/{chunk-OCKOQ3M2.js.map → chunk-N2DOU7A5.js.map} +0 -0
  125. /package/dist/{chunk-YOIZOUSY.js.map → chunk-PK2KOR6H.js.map} +0 -0
  126. /package/dist/{chunk-PB6WBFNR.js.map → chunk-PTDPY5YN.js.map} +0 -0
  127. /package/dist/{chunk-EKQND7TT.js.map → chunk-RTYBNDHE.js.map} +0 -0
  128. /package/dist/{chunk-T2P6QX4W.js.map → chunk-TARMAPO6.js.map} +0 -0
  129. /package/dist/{chunk-UXOKTRDR.js.map → chunk-TAUJUPJN.js.map} +0 -0
  130. /package/dist/{chunk-2YKGPMLS.js.map → chunk-TNIN3DPC.js.map} +0 -0
  131. /package/dist/{chunk-KPYBNLA2.js.map → chunk-TPGQIJOK.js.map} +0 -0
  132. /package/dist/{chunk-ZLYZBZ6P.js.map → chunk-UEYKYTJD.js.map} +0 -0
  133. /package/dist/{chunk-7PNHK54L.js.map → chunk-W3DLKUOV.js.map} +0 -0
  134. /package/dist/{chunk-6WZV65AF.js.map → chunk-WSHOJMQG.js.map} +0 -0
  135. /package/dist/{client-MAH6EO3E.js.map → client-XITH4RAT.js.map} +0 -0
  136. /package/dist/{config-LLC2SVQY.js.map → config-YYD7E5BT.js.map} +0 -0
  137. /package/dist/{config-mutate-2AGZLP25.js.map → config-mutate-F23A3UAU.js.map} +0 -0
  138. /package/dist/{config-mutator-REAOL7IJ.js.map → config-mutator-XHSEEKWW.js.map} +0 -0
  139. /package/dist/{contributions-PJ56BN7H.js.map → contributions-R2BJWBI7.js.map} +0 -0
  140. /package/dist/{doctor-GUOMJIP2.js.map → decision-approvals-NJS2ARAF.js.map} +0 -0
  141. /package/dist/{hub-YOXHLMFE.js.map → doctor-2GK4QVSK.js.map} +0 -0
  142. /package/dist/{follow-up-tool-WJDVBIKK.js.map → follow-up-tool-FT5JYKSI.js.map} +0 -0
  143. /package/dist/{promote-JFNEREPV.js.map → hub-QBJH2GAV.js.map} +0 -0
  144. /package/dist/{org-tool-DSNS2U6J.js.map → org-tool-BTZF5L74.js.map} +0 -0
  145. /package/dist/{query-AZV6567L.js.map → owner-decisions-D3MBTX4D.js.map} +0 -0
  146. /package/dist/{registry-FE6NJMV3.js.map → promote-JQYV4QKG.js.map} +0 -0
  147. /package/dist/{routing-MLJJ3R3V.js.map → query-RW3BV23C.js.map} +0 -0
  148. /package/dist/{query-settings-NVR6KLT6.js.map → query-settings-DN6BU3QA.js.map} +0 -0
  149. /package/dist/{schedule-tool-TVM4RJ35.js.map → registry-CQLEJUHN.js.map} +0 -0
  150. /package/dist/{request-planner-63YQLEPP.js.map → request-planner-M4GOEJUD.js.map} +0 -0
  151. /package/dist/{review-candidates-MMCISAK2.js.map → review-candidates-HZDY5DV3.js.map} +0 -0
  152. /package/dist/{scheduler-S3KOAAFU.js.map → routing-IUE6GT6T.js.map} +0 -0
  153. /package/dist/{seat-JXZWBSGZ.js.map → schedule-tool-WAXHHKSR.js.map} +0 -0
  154. /package/dist/{self-CICDOU3F.js.map → scheduler-PPKHYCMH.js.map} +0 -0
  155. /package/dist/{wiki-GP52MJ6Y.js.map → seat-OIVGQP4P.js.map} +0 -0
  156. /package/dist/{select-FSV56KVJ.js.map → select-TKODF5NC.js.map} +0 -0
  157. /package/dist/{wiki-enrich-M7YDGFIY.js.map → self-HICJTWYO.js.map} +0 -0
  158. /package/dist/{set-enabled-53DEYHY3.js.map → set-enabled-B3A2VMDN.js.map} +0 -0
  159. /package/dist/{sprint-tool-PYRQIJKM.js.map → sprint-tool-N4RLQ3EN.js.map} +0 -0
  160. /package/dist/{tool-O73Q2WWD.js.map → tool-FQY3IU4B.js.map} +0 -0
  161. /package/dist/{tool-YEH3GUG6.js.map → tool-FUEAREQB.js.map} +0 -0
  162. /package/dist/{tool-JKDVJJD4.js.map → tool-SBFQKJ4J.js.map} +0 -0
  163. /package/dist/{tool-4N5XR4XV.js.map → tool-UL673LK6.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{c as w}from"./chunk-76H4PAOZ.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
1
+ import{c as w}from"./chunk-4GS2I57L.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
2
2
  ${a.content}`),t.previous??""].join(`
3
3
  `),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
4
4
  `).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
33
33
  {"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
34
34
  `)+`
35
35
  `}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
36
- //# sourceMappingURL=chunk-PL5CJYNG.js.map
36
+ //# sourceMappingURL=chunk-EP3XCCZ3.js.map
@@ -1,4 +1,4 @@
1
- import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-YOXHLMFE.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-Q3HCFXDT.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-MZMIQ3SV.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-MZMIQ3SV.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
1
+ import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-QBJH2GAV.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-Q3HCFXDT.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-MZMIQ3SV.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-MZMIQ3SV.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
2
2
  `).slice(0,12).map(n=>` | ${n}`).join(`
3
3
  `)))}u.outcomes.length===0&&console.log(t.dim(" nothing to do: no entity of these types changed since the last run (--force redoes them)")),console.log(t.dim(` spent $${u.costUsd.toFixed(3)} of $${w}${u.capped?" \xB7 stopped at the cap":""}`))})}export{N as a,I as b};
4
- //# sourceMappingURL=chunk-3S7ZOYP7.js.map
4
+ //# sourceMappingURL=chunk-F3DCWMTS.js.map
@@ -1,4 +1,4 @@
1
- import{b as W,c as K}from"./chunk-PB6WBFNR.js";import{h as z,j as Z}from"./chunk-3UOTLMXD.js";import{a as I,b as V}from"./chunk-FCPTN6NF.js";import{a as H,b as De}from"./chunk-7I7IEX4S.js";import{d as Y}from"./chunk-QIJLFPWE.js";import{execFile as tt}from"child_process";import{writeFileSync as Ee,mkdirSync as P,existsSync as D,readFileSync as nt}from"fs";import{resolve as _}from"path";var Ne=["off","shadow","authoritative"],xe={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},Se="INTENT_LEDGER_MODE";function q(n,e=process.env){let t=Q(e[xe[n]]);if(t)return t;let r=Q(e[Se]);return r||"off"}function Q(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return Ne.includes(e)?e:null}V();import we from"better-sqlite3";import{existsSync as ut,mkdirSync as $e}from"fs";import{dirname as Oe,resolve as Le}from"path";var T=class{db;path;constructor(e={}){this.path=Le(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),$e(Oe(this.path),{recursive:!0}),this.db=new we(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ce(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let r=this.findEventBySourceId(e.source,e.sourceEventId);if(r)return r}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
1
+ import{b as W,c as K}from"./chunk-PTDPY5YN.js";import{h as z,j as Z}from"./chunk-3UOTLMXD.js";import{a as I,b as V}from"./chunk-FCPTN6NF.js";import{a as H,b as De}from"./chunk-7I7IEX4S.js";import{d as Y}from"./chunk-QIJLFPWE.js";import{execFile as tt}from"child_process";import{writeFileSync as Ee,mkdirSync as P,existsSync as D,readFileSync as nt}from"fs";import{resolve as _}from"path";var Ne=["off","shadow","authoritative"],xe={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},Se="INTENT_LEDGER_MODE";function q(n,e=process.env){let t=Q(e[xe[n]]);if(t)return t;let r=Q(e[Se]);return r||"off"}function Q(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return Ne.includes(e)?e:null}V();import we from"better-sqlite3";import{existsSync as ut,mkdirSync as $e}from"fs";import{dirname as Oe,resolve as Le}from"path";var T=class{db;path;constructor(e={}){this.path=Le(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),$e(Oe(this.path),{recursive:!0}),this.db=new we(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ce(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let r=this.findEventBySourceId(e.source,e.sourceEventId);if(r)return r}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
2
2
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let r=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
3
3
  FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return r?j(r):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
4
4
  FROM intent_events WHERE id = ?`).get(e);return t?j(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
@@ -142,4 +142,4 @@ ${k(O(ye(c.block,F(o.brief,i.prompt)),i.report),i.expectExitZero)}`,i.maxOutputT
142
142
  `);return t.length<=e?t.join(`
143
143
  `):t.slice(-e).join(`
144
144
  `)}function st(n,e,t){return new Promise((r,i)=>{tt("/bin/sh",["-c",n],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(o,s,a)=>{if(o&&o.killed){i(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}r({stdout:String(s??""),stderr:String(a??""),code:o?typeof o.code=="number"?o.code:1:0})})})}export{T as a,te as b,St as c,wt as d,Ye as e,$t as f,Ot as g,w as h,de as i,q as j,pt as k,re as l,se as m,At as n,et as o,it as p,Ie as q,Te as r,Re as s,B as t,U as u};
145
- //# sourceMappingURL=chunk-MM7CVLQ4.js.map
145
+ //# sourceMappingURL=chunk-GCR3KWCV.js.map
@@ -1,2 +1,2 @@
1
- import{b as m,d as g,f as i,g as h}from"./chunk-5ELIX7BQ.js";import{a as f}from"./chunk-7AB3QUGH.js";import{b as l}from"./chunk-IFUAP7UD.js";import{readFileSync as p,statSync as T}from"fs";import{resolve as y}from"path";function A(a,o=process.cwd()){let e=y(o,a),n;try{n=T(e).size}catch{throw new i(`No file at ${e}.`)}if(n>m)throw new i(`The picture is ${(n/(1024*1024)).toFixed(1)} MB; the limit is 1 MB. Make it smaller and try again.`,413);let r=p(e);return h(r),r}async function N(a,o,e){let n=e.env??process.env,r=e.agentId??n.AGENTX_AGENT_ID?.trim();if(!r)return{ok:!1,message:"This is not an agent's run (AGENTX_AGENT_ID is not set)."};if(o&&o!==r)return{ok:!1,message:`An agent can only change its own picture: you are "${r}", not "${o}". Ask the owner to change it in Settings.`};let c=l(n);if(!Object.keys(c).length)return{ok:!1,message:"This run carries no proof of who you are (AGENTX_TASK_ID, or AGENTX_CHANNEL and AGENTX_CHAT_ID). Ask the owner to set the picture in Settings."};let s;if(a!==null)try{s=A(a,e.cwd)}catch(t){return{ok:!1,message:t.message}}let d=`${e.daemonUrl.replace(/\/+$/,"")}${g}?agent=${encodeURIComponent(r)}`;try{let t=await(e.fetch??fetch)(d,{method:s?"PUT":"DELETE",headers:{...c,...s?{"Content-Type":"application/octet-stream"}:{}},body:s,signal:AbortSignal.timeout(3e4)}),u=await t.json().catch(()=>({}));return t.ok?s?{ok:!0,message:`Your picture is set. It shows on the ${f}, the Org page and Settings on their next load.`}:{ok:!0,message:u.removed?"Your picture is removed; your initials show again.":"You had no picture; nothing changed."}:{ok:!1,message:u?.error||`HTTP ${t.status}`}}catch(t){return{ok:!1,message:`Couldn't reach the daemon at ${e.daemonUrl} (${t?.message??t}).`}}}export{A as a,N as b};
2
- //# sourceMappingURL=chunk-7YKVNEQ6.js.map
1
+ import{b as m,d as g,f as i,g as h}from"./chunk-5ELIX7BQ.js";import{b as l}from"./chunk-IFUAP7UD.js";import{a as f}from"./chunk-7AB3QUGH.js";import{readFileSync as p,statSync as T}from"fs";import{resolve as y}from"path";function A(a,o=process.cwd()){let e=y(o,a),n;try{n=T(e).size}catch{throw new i(`No file at ${e}.`)}if(n>m)throw new i(`The picture is ${(n/(1024*1024)).toFixed(1)} MB; the limit is 1 MB. Make it smaller and try again.`,413);let r=p(e);return h(r),r}async function N(a,o,e){let n=e.env??process.env,r=e.agentId??n.AGENTX_AGENT_ID?.trim();if(!r)return{ok:!1,message:"This is not an agent's run (AGENTX_AGENT_ID is not set)."};if(o&&o!==r)return{ok:!1,message:`An agent can only change its own picture: you are "${r}", not "${o}". Ask the owner to change it in Settings.`};let c=l(n);if(!Object.keys(c).length)return{ok:!1,message:"This run carries no proof of who you are (AGENTX_TASK_ID, or AGENTX_CHANNEL and AGENTX_CHAT_ID). Ask the owner to set the picture in Settings."};let s;if(a!==null)try{s=A(a,e.cwd)}catch(t){return{ok:!1,message:t.message}}let d=`${e.daemonUrl.replace(/\/+$/,"")}${g}?agent=${encodeURIComponent(r)}`;try{let t=await(e.fetch??fetch)(d,{method:s?"PUT":"DELETE",headers:{...c,...s?{"Content-Type":"application/octet-stream"}:{}},body:s,signal:AbortSignal.timeout(3e4)}),u=await t.json().catch(()=>({}));return t.ok?s?{ok:!0,message:`Your picture is set. It shows on the ${f}, the Org page and Settings on their next load.`}:{ok:!0,message:u.removed?"Your picture is removed; your initials show again.":"You had no picture; nothing changed."}:{ok:!1,message:u?.error||`HTTP ${t.status}`}}catch(t){return{ok:!1,message:`Couldn't reach the daemon at ${e.daemonUrl} (${t?.message??t}).`}}}export{A as a,N as b};
2
+ //# sourceMappingURL=chunk-GMP2IB4E.js.map
@@ -1,3 +1,3 @@
1
- import{Sb as $,pb as S}from"./chunk-KT4CZ7GY.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as y,writeFileSync as C}from"fs";import{resolve as c}from"path";function m(t){return c(t,".agentx","email")}function u(t,e){k(c(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
1
+ import{Zb as $,wb as S}from"./chunk-NWY4OF4X.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as y,writeFileSync as C}from"fs";import{resolve as c}from"path";function m(t){return c(t,".agentx","email")}function u(t,e){k(c(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
2
2
  `,{mode:384}),E(r,t)}function g(t){try{return JSON.parse(j(t,"utf-8"))}catch{return null}}var D=t=>c(m(t),"threads.json");function w(t){return g(D(t))??{}}function I(t,e){return w(t)[e.toLowerCase()]}function L(t,e){let r=w(t);r[e.to.toLowerCase()]=e,u(D(t),r)}var h=(t,e)=>c(m(t),"cursors",`${e}.json`);function z(t,e){return g(h(t,e))}function B(t,e,r){u(h(t,e),r)}var T=2e4,_=t=>c(m(t),"drafts"),N=t=>/^[a-z0-9-]{8,64}$/.test(t),a=(t,e)=>c(_(t),`${e}.json`);function U(t,e,r=Date.now()){let n=e.text.trim().slice(0,T);if(!n)throw new Error("empty reply");let s={...e,text:n,id:`${r.toString(36)}-${x(4).toString("hex")}`,status:"pending",created_at:new Date(r).toISOString()};return u(a(t,s.id),s),s}function v(t,e){return N(e)?g(a(t,e)):null}function V(t,e){let r=_(t);return b(r)?M(r).filter(n=>n.endsWith(".json")).map(n=>v(t,n.slice(0,-5))).filter(n=>!!n&&(!e||n.status===e)).sort((n,s)=>n.created_at.localeCompare(s.created_at)):[]}async function W(t,e,r,n){let s=v(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no email reply "${e}" is waiting`};let i=`${a(t,e)}.${process.pid}.${x(3).toString("hex")}.claim`;try{E(a(t,e),i)}catch{return{ok:!1,error:`email reply "${e}" is already being decided`}}let d=n.text!==void 0&&n.text.trim()!==""&&n.text.trim()!==s.text,o={...s,...d?{text:n.text.trim().slice(0,T),edited:!0}:{},decided_by:n.by??"operator",decided_at:new Date(n.now??Date.now()).toISOString()};if(r==="no")o.status="rejected";else{let f=await n.send(o).catch(p=>({ok:!1,error:String(p?.message??p)}));if(!f.ok){u(a(t,e),{...s,error:f.error});try{y(i)}catch{}return{ok:!1,error:`not sent: ${f.error}`}}o.status="sent",delete o.error}u(a(t,e),o);try{y(i)}catch{}return{ok:!0,draft:o}}$();function l(t,e){return(t??"").replace(/\$\{(\w+)\}/g,(r,n)=>e[n]??"")}function P(t,e=process.env){let r={host:t.imap.host,port:t.imap.port,secure:t.imap.secure,user:l(t.imap.user,e)||t.address,password:l(t.imap.password,e)},n={host:t.smtp.host,port:t.smtp.port,secure:t.smtp.secure,user:l(t.smtp.user,e)||r.user,password:l(t.smtp.password,e)||r.password};return{imap:r,smtp:n}}async function R(t,e,r,n=process.env){let{smtp:s}=P(t,n);if(!s.password)throw new Error(`no SMTP password for ${t.address}: set it in .env`);return J(s,{name:e,address:t.address},r,{"Auto-Submitted":"auto-replied"})}async function J(t,e,r,n){let{default:s}=await import("nodemailer"),i=s.createTransport({host:t.host,port:t.port,secure:t.secure,auth:{user:t.user,pass:t.password},connectionTimeout:2e4,greetingTimeout:2e4,socketTimeout:6e4});try{return(await i.sendMail({from:e,to:r.toName?{name:r.toName,address:r.to}:r.to,subject:r.subject,text:r.text,...r.inReplyTo?{inReplyTo:r.inReplyTo}:{},...r.references?{references:r.references}:{},headers:n})).messageId}finally{i.close()}}function G(t,e){return async r=>{let n=t?.channels?.email?.accounts?.[r.account];if(!n)return{ok:!1,error:`no email account "${r.account}" in agentx.json`};let s=S.safeParse(n);if(!s.success)return{ok:!1,error:`email account "${r.account}": ${s.error.issues[0]?.message}`};let i=s.data,d=i.name||t?.agents?.[r.agent]?.name||r.agent;return await R(i,d,{to:r.to,toName:r.to_name,subject:r.subject,inReplyTo:r.in_reply_to,references:r.references,text:r.text},e),{ok:!0}}}export{I as a,L as b,z as c,B as d,U as e,v as f,V as g,W as h,P as i,R as j,J as k,G as l};
3
- //# sourceMappingURL=chunk-G72NZCOM.js.map
3
+ //# sourceMappingURL=chunk-H22TBFXT.js.map
@@ -1,4 +1,4 @@
1
- import{a as h}from"./chunk-44CTJ3Q7.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
1
+ import{a as h}from"./chunk-4CGAIVLW.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
2
2
  `),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
3
3
  `),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
4
- //# sourceMappingURL=chunk-SXCRQMNL.js.map
4
+ //# sourceMappingURL=chunk-KI2M5LXX.js.map
@@ -0,0 +1,13 @@
1
+ var d=7,h=6;function c(l){let a=l.replace(/^---[\s\S]*?\n---\n/,""),n=[],o=/^##\s+([^\n]*)\n([\s\S]*?)(?=^##\s|(?![\s\S]))/gm;for(let t=o.exec(a);t;t=o.exec(a))n.push({head:t[1].trim(),text:t[2]});let r=t=>t.replace(/<!--[\s\S]*?-->/g,"").replace(/\n{3,}/g,`
2
+
3
+ `).trim(),e=n.filter(t=>/^(update|change|amend)/i.test(t.head)),s=n.find(t=>/^rule\b/i.test(t.head)&&!/superseded|earlier rule/i.test(t.head)),i;return e.length?(i=[...e].reverse().map(t=>`${t.head}:
4
+ ${r(t.text)}`).join(`
5
+
6
+ `),s&&(i+=`
7
+
8
+ Older rule (the updates above win where they differ):
9
+ ${r(s.text)}`)):i=r(s?s.text:a),i.length>1400?i.slice(0,1400-1)+"\u2026":i}function m(l,a,n={}){let o=a-(n.days??7)*864e5,r=l.filter(e=>e.meta.type==="decision"&&!e.path.includes("/_versions/")).map(e=>({a:e,at:Date.parse(e.meta.lastUpdated||e.meta.created||"")})).filter(e=>Number.isFinite(e.at)&&e.at>=o).sort((e,s)=>s.at-e.at).slice(0,n.max??6);return r.length===0?"":["[Owner decisions \u2014 the newest recorded rulings, from the wiki]","These outrank the chat history, the continuity memo and your own notes below. Where those say something else (an approval still needed, a step still waiting), they are out of date: follow these.",...r.map(({a:e})=>`
10
+ ### ${e.meta.title} (updated ${e.meta.lastUpdated||e.meta.created})
11
+ ${c(e.content)}`),"[End owner decisions]"].join(`
12
+ `)}export{d as a,h as b,c,m as d};
13
+ //# sourceMappingURL=chunk-KWWBDLE6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agents/owner-decisions.ts"],"sourcesContent":["// --- Owner decisions on a fresh session ---\n//\n// A fresh session (first turn, or after a rotation) is handed the chat's\n// recent history and a continuity memo from the session before it. Both\n// can be hours old. On 2026-11-07 a rotated session read its own earlier\n// reply in the history (\"needs your yes on Telegram for five steps\") and\n// repeated it to the owner, although the owner had removed those yeses an\n// hour before and the work had already merged. The wiki held the newer\n// decision, but a fresh session only sees the wiki's catalog of titles.\n//\n// This block puts the newest decision articles, with their rule text,\n// ahead of the history and the memo, and says they win where those\n// disagree. Fresh sessions only, like the catalog: a resumed session\n// already saw it.\n\nimport type { WikiArticle } from \"@/wiki/types\"\n\nexport const DECISION_DAYS = 7\nexport const MAX_DECISIONS = 6\nconst RULE_CLIP = 1400\n\n/** The rule of a decision article, newest first. Decision pages are often\n * appended to (\"## Update <date> ...\" below an older \"## Rule\"), so the\n * latest update comes first and the older rule last, marked as older.\n * With neither heading, the start of the body. */\nexport function ruleText(content: string): string {\n const body = content.replace(/^---[\\s\\S]*?\\n---\\n/, \"\")\n const sections: Array<{ head: string; text: string }> = []\n const re = /^##\\s+([^\\n]*)\\n([\\s\\S]*?)(?=^##\\s|(?![\\s\\S]))/gm\n for (let m = re.exec(body); m; m = re.exec(body)) sections.push({ head: m[1].trim(), text: m[2] })\n const clean = (t: string) => t.replace(/<!--[\\s\\S]*?-->/g, \"\").replace(/\\n{3,}/g, \"\\n\\n\").trim()\n const updates = sections.filter((x) => /^(update|change|amend)/i.test(x.head))\n const rule = sections.find((x) => /^rule\\b/i.test(x.head) && !/superseded|earlier rule/i.test(x.head))\n let text: string\n if (updates.length) {\n text = [...updates].reverse().map((u) => `${u.head}:\\n${clean(u.text)}`).join(\"\\n\\n\")\n if (rule) text += `\\n\\nOlder rule (the updates above win where they differ):\\n${clean(rule.text)}`\n } else {\n text = clean(rule ? rule.text : body)\n }\n return text.length > RULE_CLIP ? text.slice(0, RULE_CLIP - 1) + \"…\" : text\n}\n\nexport function buildOwnerDecisions(articles: WikiArticle[], now: number, opts: { days?: number; max?: number } = {}): string {\n const since = now - (opts.days ?? DECISION_DAYS) * 86_400_000\n const recent = articles\n .filter((a) => a.meta.type === \"decision\" && !a.path.includes(\"/_versions/\"))\n .map((a) => ({ a, at: Date.parse(a.meta.lastUpdated || a.meta.created || \"\") }))\n .filter((x) => Number.isFinite(x.at) && x.at >= since)\n .sort((x, y) => y.at - x.at)\n .slice(0, opts.max ?? MAX_DECISIONS)\n if (recent.length === 0) return \"\"\n return [\n \"[Owner decisions — the newest recorded rulings, from the wiki]\",\n \"These outrank the chat history, the continuity memo and your own notes below. Where those say something else (an approval still needed, a step still waiting), they are out of date: follow these.\",\n ...recent.map(({ a }) => `\\n### ${a.meta.title} (updated ${a.meta.lastUpdated || a.meta.created})\\n${ruleText(a.content)}`),\n \"[End owner decisions]\",\n ].join(\"\\n\")\n}\n"],"mappings":"AAiBO,IAAMA,EAAgB,EAChBC,EAAgB,EAOtB,SAASC,EAASC,EAAyB,CAChD,IAAMC,EAAOD,EAAQ,QAAQ,sBAAuB,EAAE,EAChDE,EAAkD,CAAC,EACnDC,EAAK,mDACX,QAASC,EAAID,EAAG,KAAKF,CAAI,EAAGG,EAAGA,EAAID,EAAG,KAAKF,CAAI,EAAGC,EAAS,KAAK,CAAE,KAAME,EAAE,CAAC,EAAE,KAAK,EAAG,KAAMA,EAAE,CAAC,CAAE,CAAC,EACjG,IAAMC,EAAS,GAAc,EAAE,QAAQ,mBAAoB,EAAE,EAAE,QAAQ,UAAW;AAAA;AAAA,CAAM,EAAE,KAAK,EACzFC,EAAUJ,EAAS,OAAQK,GAAM,0BAA0B,KAAKA,EAAE,IAAI,CAAC,EACvEC,EAAON,EAAS,KAAMK,GAAM,WAAW,KAAKA,EAAE,IAAI,GAAK,CAAC,2BAA2B,KAAKA,EAAE,IAAI,CAAC,EACjGE,EACJ,OAAIH,EAAQ,QACVG,EAAO,CAAC,GAAGH,CAAO,EAAE,QAAQ,EAAE,IAAKI,GAAM,GAAGA,EAAE;AAAA,EAAUL,EAAMK,EAAE,IAAI,GAAG,EAAE,KAAK;AAAA;AAAA,CAAM,EAChFF,IAAMC,GAAQ;AAAA;AAAA;AAAA,EAA8DJ,EAAMG,EAAK,IAAI,MAE/FC,EAAOJ,EAAMG,EAAOA,EAAK,KAAOP,CAAI,EAE/BQ,EAAK,OAAS,KAAYA,EAAK,MAAM,EAAG,KAAY,CAAC,EAAI,SAAMA,CACxE,CAEO,SAASE,EAAoBC,EAAyBC,EAAaC,EAAwC,CAAC,EAAW,CAC5H,IAAMC,EAAQF,GAAOC,EAAK,MAAQ,GAAiB,MAC7CE,EAASJ,EACZ,OAAQK,GAAMA,EAAE,KAAK,OAAS,YAAc,CAACA,EAAE,KAAK,SAAS,aAAa,CAAC,EAC3E,IAAKA,IAAO,CAAE,EAAAA,EAAG,GAAI,KAAK,MAAMA,EAAE,KAAK,aAAeA,EAAE,KAAK,SAAW,EAAE,CAAE,EAAE,EAC9E,OAAQV,GAAM,OAAO,SAASA,EAAE,EAAE,GAAKA,EAAE,IAAMQ,CAAK,EACpD,KAAK,CAACR,EAAGW,IAAMA,EAAE,GAAKX,EAAE,EAAE,EAC1B,MAAM,EAAGO,EAAK,KAAO,CAAa,EACrC,OAAIE,EAAO,SAAW,EAAU,GACzB,CACL,sEACA,qMACA,GAAGA,EAAO,IAAI,CAAC,CAAE,EAAAC,CAAE,IAAM;AAAA,MAASA,EAAE,KAAK,kBAAkBA,EAAE,KAAK,aAAeA,EAAE,KAAK;AAAA,EAAalB,EAASkB,EAAE,OAAO,GAAG,EAC1H,uBACF,EAAE,KAAK;AAAA,CAAI,CACb","names":["DECISION_DAYS","MAX_DECISIONS","ruleText","content","body","sections","re","m","clean","updates","x","rule","text","u","buildOwnerDecisions","articles","now","opts","since","recent","a","y"]}
@@ -0,0 +1,4 @@
1
+ import{createHash as c}from"crypto";import{existsSync as l,mkdirSync as d,readFileSync as u,renameSync as f,writeFileSync as v}from"fs";import{dirname as g,resolve as A}from"path";function s(e){return A(e,"_decisions","approved.json")}function p(e){return c("sha256").update(`${e.meta.title??""}
2
+ ${(e.content??"").trim()}`).digest("hex")}function i(e){let n=s(e);if(!l(n))return{};try{let t=JSON.parse(u(n,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function a(e,n){let t=s(e);d(g(t),{recursive:!0});let r=`${t}.${process.pid}.tmp`;v(r,JSON.stringify(n,null,2)+`
3
+ `),f(r,t)}function m(e,n){let t=n[e.path];return t?t.hash===p(e)?"approved":"changed":"waiting"}function y(e,n){return e.filter(t=>t.meta.type!=="decision"||m(t,n)==="approved")}function S(e,n,t){return t?y(e,i(n)):e}function k(e=process.env){return e.AGENTX_AGENT_ID?.trim()||e.AGENTX_TASK_ID?.trim()?"decision pages are approved by the owner from a terminal, not from inside an agent's run":null}function w(e,n,t={}){if(n.meta.type!=="decision")throw new Error(`${n.path} is not a decision page (type: ${n.meta.type??"none"})`);let r=i(e),o={hash:p(n),approvedAt:new Date(t.now??Date.now()).toISOString(),by:t.by||"owner",lastUpdated:n.meta.lastUpdated||void 0,...t.note?{note:t.note}:{}};return r[n.path]=o,a(e,r),o}function b(e,n){let t=i(e);return t[n]?(delete t[n],a(e,t),!0):!1}export{s as a,p as b,i as c,m as d,y as e,S as f,k as g,w as h,b as i};
4
+ //# sourceMappingURL=chunk-LIY5CHUV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/decision-approvals.ts"],"sourcesContent":["// --- Owner approval for decision pages (#1778) ---\n//\n// A fresh session puts the newest wiki `decision` pages ahead of the chat\n// history and says they win (agents/owner-decisions.ts, #1777). Until now\n// any write could make such a page: the absorb job types pages from raw\n// chat and cron entries (a client's message included), `wiki patch` and\n// `wiki interview` take an agent id from the caller, the daily\n// contributions can create pages, and mesh sync copies a peer's pages.\n// None of them asks the owner. So one unreviewed write could steer every\n// fresh session of that agent.\n//\n// The gate is off unless `wiki.decisionApprovals.required` is set. When on,\n// a decision page reaches that block only while its title and\n// body are exactly what the owner approved. The approval is kept outside\n// the pages, in `_decisions/approved.json` of the agent's wiki, which no\n// page write touches and the article index skips (`_` prefix). Any later\n// edit, by anyone, changes the hash, and the page waits for a new\n// approval. The owner approves from a terminal; the command refuses inside\n// an agent's run.\n\nimport { createHash } from \"crypto\"\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport type { WikiArticle } from \"./types\"\n\nexport interface DecisionApproval {\n /** Hash of the title and body the owner approved. */\n hash: string\n approvedAt: string\n by: string\n /** The page's own `last_updated` when approved, for the listing. */\n lastUpdated?: string\n note?: string\n}\n\nexport type DecisionApprovals = Record<string, DecisionApproval>\n\n/** Where a wiki's approvals live. */\nexport function approvalsFile(wikiBaseDir: string): string {\n return resolve(wikiBaseDir, \"_decisions\", \"approved.json\")\n}\n\n/** What an approval covers: the title and the body, whitespace at the ends\n * ignored. Frontmatter dates and tags are not part of it. */\nexport function decisionHash(article: Pick<WikiArticle, \"meta\" | \"content\">): string {\n return createHash(\"sha256\")\n .update(`${article.meta.title ?? \"\"}\\n${(article.content ?? \"\").trim()}`)\n .digest(\"hex\")\n}\n\nexport function readApprovals(wikiBaseDir: string): DecisionApprovals {\n const file = approvalsFile(wikiBaseDir)\n if (!existsSync(file)) return {}\n try {\n const parsed = JSON.parse(readFileSync(file, \"utf-8\"))\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed as DecisionApprovals : {}\n } catch {\n return {} // unreadable: nothing counts as approved\n }\n}\n\nfunction writeApprovals(wikiBaseDir: string, all: DecisionApprovals): void {\n const file = approvalsFile(wikiBaseDir)\n mkdirSync(dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(all, null, 2) + \"\\n\")\n renameSync(tmp, file)\n}\n\nexport type DecisionState = \"approved\" | \"changed\" | \"waiting\"\n\n/** approved: the page is what the owner approved. changed: approved once,\n * edited since. waiting: never approved. */\nexport function decisionState(article: WikiArticle, approvals: DecisionApprovals): DecisionState {\n const a = approvals[article.path]\n if (!a) return \"waiting\"\n return a.hash === decisionHash(article) ? \"approved\" : \"changed\"\n}\n\n/** Decision pages as they may reach the owner-decisions block: approved\n * ones only. Other page types pass through unchanged. */\nexport function approvedDecisionsOnly(articles: WikiArticle[], approvals: DecisionApprovals): WikiArticle[] {\n return articles.filter((a) => a.meta.type !== \"decision\" || decisionState(a, approvals) === \"approved\")\n}\n\n/** What the owner-decisions block may read. With approvals not required\n * (the default, `wiki.decisionApprovals.required`), every page passes as\n * #1776 specifies; required, decision pages need the owner's approval. */\nexport function decisionsForBlock(articles: WikiArticle[], wikiBaseDir: string, required: boolean): WikiArticle[] {\n return required ? approvedDecisionsOnly(articles, readApprovals(wikiBaseDir)) : articles\n}\n\n/** Why the current process may not approve: inside an agent's run. */\nexport function approvalRefusal(env: NodeJS.ProcessEnv = process.env): string | null {\n if (env.AGENTX_AGENT_ID?.trim() || env.AGENTX_TASK_ID?.trim()) {\n return \"decision pages are approved by the owner from a terminal, not from inside an agent's run\"\n }\n return null\n}\n\nexport function approveDecision(\n wikiBaseDir: string,\n article: WikiArticle,\n opts: { by?: string; now?: number; note?: string } = {},\n): DecisionApproval {\n if (article.meta.type !== \"decision\") throw new Error(`${article.path} is not a decision page (type: ${article.meta.type ?? \"none\"})`)\n const all = readApprovals(wikiBaseDir)\n const approval: DecisionApproval = {\n hash: decisionHash(article),\n approvedAt: new Date(opts.now ?? Date.now()).toISOString(),\n by: opts.by || \"owner\",\n lastUpdated: article.meta.lastUpdated || undefined,\n ...(opts.note ? { note: opts.note } : {}),\n }\n all[article.path] = approval\n writeApprovals(wikiBaseDir, all)\n return approval\n}\n\n/** Remove an approval. True when there was one. */\nexport function revokeDecision(wikiBaseDir: string, path: string): boolean {\n const all = readApprovals(wikiBaseDir)\n if (!all[path]) return false\n delete all[path]\n writeApprovals(wikiBaseDir, all)\n return true\n}\n"],"mappings":"AAoBA,OAAS,cAAAA,MAAkB,SAC3B,OAAS,cAAAC,EAAY,aAAAC,EAAW,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,MAAqB,KAC/E,OAAS,WAAAC,EAAS,WAAAC,MAAe,OAgB1B,SAASC,EAAcC,EAA6B,CACzD,OAAOF,EAAQE,EAAa,aAAc,eAAe,CAC3D,CAIO,SAASC,EAAaC,EAAwD,CACnF,OAAOX,EAAW,QAAQ,EACvB,OAAO,GAAGW,EAAQ,KAAK,OAAS;AAAA,GAAQA,EAAQ,SAAW,IAAI,KAAK,GAAG,EACvE,OAAO,KAAK,CACjB,CAEO,SAASC,EAAcH,EAAwC,CACpE,IAAMI,EAAOL,EAAcC,CAAW,EACtC,GAAI,CAACR,EAAWY,CAAI,EAAG,MAAO,CAAC,EAC/B,GAAI,CACF,IAAMC,EAAS,KAAK,MAAMX,EAAaU,EAAM,OAAO,CAAC,EACrD,OAAOC,GAAU,OAAOA,GAAW,UAAY,CAAC,MAAM,QAAQA,CAAM,EAAIA,EAA8B,CAAC,CACzG,MAAE,CACA,MAAO,CAAC,CACV,CACF,CAEA,SAASC,EAAeN,EAAqBO,EAA8B,CACzE,IAAMH,EAAOL,EAAcC,CAAW,EACtCP,EAAUI,EAAQO,CAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EAC5C,IAAMI,EAAM,GAAGJ,KAAQ,QAAQ,UAC/BR,EAAcY,EAAK,KAAK,UAAUD,EAAK,KAAM,CAAC,EAAI;AAAA,CAAI,EACtDZ,EAAWa,EAAKJ,CAAI,CACtB,CAMO,SAASK,EAAcP,EAAsBQ,EAA6C,CAC/F,IAAMC,EAAID,EAAUR,EAAQ,IAAI,EAChC,OAAKS,EACEA,EAAE,OAASV,EAAaC,CAAO,EAAI,WAAa,UADxC,SAEjB,CAIO,SAASU,EAAsBC,EAAyBH,EAA6C,CAC1G,OAAOG,EAAS,OAAQF,GAAMA,EAAE,KAAK,OAAS,YAAcF,EAAcE,EAAGD,CAAS,IAAM,UAAU,CACxG,CAKO,SAASI,EAAkBD,EAAyBb,EAAqBe,EAAkC,CAChH,OAAOA,EAAWH,EAAsBC,EAAUV,EAAcH,CAAW,CAAC,EAAIa,CAClF,CAGO,SAASG,EAAgBC,EAAyB,QAAQ,IAAoB,CACnF,OAAIA,EAAI,iBAAiB,KAAK,GAAKA,EAAI,gBAAgB,KAAK,EACnD,2FAEF,IACT,CAEO,SAASC,EACdlB,EACAE,EACAiB,EAAqD,CAAC,EACpC,CAClB,GAAIjB,EAAQ,KAAK,OAAS,WAAY,MAAM,IAAI,MAAM,GAAGA,EAAQ,sCAAsCA,EAAQ,KAAK,MAAQ,SAAS,EACrI,IAAMK,EAAMJ,EAAcH,CAAW,EAC/BoB,EAA6B,CACjC,KAAMnB,EAAaC,CAAO,EAC1B,WAAY,IAAI,KAAKiB,EAAK,KAAO,KAAK,IAAI,CAAC,EAAE,YAAY,EACzD,GAAIA,EAAK,IAAM,QACf,YAAajB,EAAQ,KAAK,aAAe,OACzC,GAAIiB,EAAK,KAAO,CAAE,KAAMA,EAAK,IAAK,EAAI,CAAC,CACzC,EACA,OAAAZ,EAAIL,EAAQ,IAAI,EAAIkB,EACpBd,EAAeN,EAAaO,CAAG,EACxBa,CACT,CAGO,SAASC,EAAerB,EAAqBsB,EAAuB,CACzE,IAAMf,EAAMJ,EAAcH,CAAW,EACrC,OAAKO,EAAIe,CAAI,GACb,OAAOf,EAAIe,CAAI,EACfhB,EAAeN,EAAaO,CAAG,EACxB,IAHgB,EAIzB","names":["createHash","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","dirname","resolve","approvalsFile","wikiBaseDir","decisionHash","article","readApprovals","file","parsed","writeApprovals","all","tmp","decisionState","approvals","a","approvedDecisionsOnly","articles","decisionsForBlock","required","approvalRefusal","env","approveDecision","opts","approval","revokeDecision","path"]}
@@ -1,4 +1,4 @@
1
- import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-ROLSAEXB.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-6WZV65AF.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
1
+ import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-D55REZL3.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-WSHOJMQG.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
2
2
 
3
3
  ## Shared wiki (other agents' articles)
4
4
 
@@ -51,5 +51,5 @@ ${o}
51
51
 
52
52
  Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
53
53
 
54
- Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-LLC2SVQY.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
- //# sourceMappingURL=chunk-OCKOQ3M2.js.map
54
+ Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-YYD7E5BT.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
+ //# sourceMappingURL=chunk-N2DOU7A5.js.map