agentix-cli 0.144.0 → 0.146.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 (136) hide show
  1. package/dist/{App-N2U77ED7.js → App-EU2AJWW5.js} +2 -2
  2. package/dist/{ChatApp-GYVTECF6.js → ChatApp-ORR3U3AN.js} +2 -2
  3. package/dist/{absorb-eval-WSAVWCZV.js → absorb-eval-3VGPDRWS.js} +2 -2
  4. package/dist/{agent-SLRGXBMK.js → agent-NVJNOK5L.js} +2 -2
  5. package/dist/{board-dashboard-B3T7VCRQ.js → board-dashboard-JV2JNRWD.js} +31 -18
  6. package/dist/board-dashboard-JV2JNRWD.js.map +1 -0
  7. package/dist/{chunk-CZWEXRIE.js → chunk-3BMIZY6X.js} +2 -2
  8. package/dist/{chunk-2GJFLPS7.js → chunk-5TFXFLMN.js} +3 -3
  9. package/dist/{chunk-LVQHNTXV.js → chunk-5YAUENDI.js} +2 -2
  10. package/dist/{chunk-DFWPTNZ5.js → chunk-7O7VDA3J.js} +2 -2
  11. package/dist/{chunk-SVNYI6GR.js → chunk-DTWBB7B7.js} +2 -2
  12. package/dist/{chunk-VYLMC5DO.js → chunk-GECGRCYC.js} +2 -2
  13. package/dist/chunk-IBK7AG4S.js +62 -0
  14. package/dist/chunk-IBK7AG4S.js.map +1 -0
  15. package/dist/{chunk-UNZRZOED.js → chunk-J723FL3J.js} +2 -2
  16. package/dist/{chunk-SFUNL7RV.js → chunk-K3QDK4BX.js} +2 -2
  17. package/dist/{chunk-M7527M7D.js → chunk-MMBFAVBR.js} +2 -2
  18. package/dist/{chunk-GWBBWYGM.js → chunk-MO7DH5L6.js} +3 -3
  19. package/dist/chunk-MO7DH5L6.js.map +1 -0
  20. package/dist/chunk-MOCKFVYE.js +128 -0
  21. package/dist/chunk-MOCKFVYE.js.map +1 -0
  22. package/dist/{chunk-PJGLIAEP.js → chunk-NBDYBTI6.js} +296 -295
  23. package/dist/chunk-NBDYBTI6.js.map +1 -0
  24. package/dist/{chunk-45TKVOJX.js → chunk-O7ZJS33Z.js} +2 -2
  25. package/dist/{chunk-MXWAREAQ.js → chunk-OEB6RTRA.js} +2 -2
  26. package/dist/{chunk-4JHMV3D3.js → chunk-OT5KLHUT.js} +2 -2
  27. package/dist/{chunk-QI4FYJGJ.js → chunk-QNS3WHGU.js} +2 -2
  28. package/dist/{chunk-EX4AREN5.js → chunk-SK24JFEK.js} +2 -2
  29. package/dist/{chunk-TTBCXVPJ.js → chunk-SNCRLEH3.js} +78 -78
  30. package/dist/chunk-SNCRLEH3.js.map +1 -0
  31. package/dist/{chunk-KV4ZA7FS.js → chunk-TJZGAKIB.js} +4 -4
  32. package/dist/{chunk-KV4ZA7FS.js.map → chunk-TJZGAKIB.js.map} +1 -1
  33. package/dist/{chunk-BAO77R4L.js → chunk-TYONASHA.js} +2 -2
  34. package/dist/{chunk-R5VGRKUW.js → chunk-TZVJP4H3.js} +2 -2
  35. package/dist/{chunk-Q73QQPDB.js → chunk-UFX6INNI.js} +2 -2
  36. package/dist/{chunk-JGX5IWNX.js → chunk-USTNT7P7.js} +2 -2
  37. package/dist/{chunk-UII54DAP.js → chunk-UTYNYG7M.js} +2 -2
  38. package/dist/{chunk-RV4WJZW5.js → chunk-UVJLIHLL.js} +2 -2
  39. package/dist/{chunk-RGBQULXX.js → chunk-UYLVSS6I.js} +2 -2
  40. package/dist/{chunk-GOAMSJ2D.js → chunk-WCOT35YG.js} +2 -2
  41. package/dist/cli.js +1 -1
  42. package/dist/{client-B7FXDTYK.js → client-6KZZKCN2.js} +2 -2
  43. package/dist/config-W6JNVPBY.js +2 -0
  44. package/dist/{config-mutate-XQRUAVEH.js → config-mutate-57YT7BNB.js} +2 -2
  45. package/dist/config-mutator-6NWQPE7K.js +2 -0
  46. package/dist/{contributions-ESUSYUQG.js → contributions-Y6B6LG7X.js} +2 -2
  47. package/dist/{doctor-DIYZGSIS.js → doctor-ZP4KADAD.js} +2 -2
  48. package/dist/{follow-up-tool-QXEYEWX7.js → follow-up-tool-5AMZKVI4.js} +2 -2
  49. package/dist/{grants-MM7U6GCK.js → grants-O7SJ2J4B.js} +2 -2
  50. package/dist/{hub-OC7PH2AR.js → hub-BZF3ZYQ5.js} +2 -2
  51. package/dist/index.d.ts +188 -0
  52. package/dist/index.js +1 -1
  53. package/dist/{program-LZPM6I2Q.js → program-MO7HLAP5.js} +190 -190
  54. package/dist/program-MO7HLAP5.js.map +1 -0
  55. package/dist/{promote-SIC6RWCX.js → promote-IJANZNQK.js} +2 -2
  56. package/dist/{query-OP2MSR2G.js → query-DC74NB3R.js} +2 -2
  57. package/dist/{query-settings-67332F5V.js → query-settings-RXFOATOZ.js} +2 -2
  58. package/dist/{registry-G2ZG5TIN.js → registry-24IXRDWX.js} +2 -2
  59. package/dist/{request-planner-THTPE3FP.js → request-planner-33CWWCJU.js} +2 -2
  60. package/dist/{review-candidates-7PS7CHXF.js → review-candidates-ENWB6LHD.js} +2 -2
  61. package/dist/{routing-PE7DB7WA.js → routing-AUFJ4MNP.js} +2 -2
  62. package/dist/schedule-tool-NAMOBMZE.js +2 -0
  63. package/dist/{scheduler-YTXCIQTZ.js → scheduler-KWSBBZKW.js} +2 -2
  64. package/dist/{seat-6DMK4274.js → seat-YGMLJ6KS.js} +2 -2
  65. package/dist/{select-CLDYPAOS.js → select-JJGBM6ZT.js} +2 -2
  66. package/dist/{set-enabled-ZH2DH4GU.js → set-enabled-THE7QIGQ.js} +2 -2
  67. package/dist/{tool-MKDTKBJ4.js → tool-4ACTSFKC.js} +2 -2
  68. package/dist/{tool-4AO3ZMAY.js → tool-6LR6VORJ.js} +4 -4
  69. package/dist/tool-6LR6VORJ.js.map +1 -0
  70. package/dist/{wiki-CH2HYJVI.js → wiki-YAW7UEOQ.js} +2 -2
  71. package/dist/wiki-enrich-6ANFA2VB.js +2 -0
  72. package/package.json +1 -1
  73. package/dist/board-dashboard-B3T7VCRQ.js.map +0 -1
  74. package/dist/chunk-3LAQ74H7.js +0 -128
  75. package/dist/chunk-3LAQ74H7.js.map +0 -1
  76. package/dist/chunk-DPIQCHXB.js +0 -62
  77. package/dist/chunk-DPIQCHXB.js.map +0 -1
  78. package/dist/chunk-GWBBWYGM.js.map +0 -1
  79. package/dist/chunk-PJGLIAEP.js.map +0 -1
  80. package/dist/chunk-TTBCXVPJ.js.map +0 -1
  81. package/dist/config-MLP33NWR.js +0 -2
  82. package/dist/config-mutator-5JFTMQ43.js +0 -2
  83. package/dist/program-LZPM6I2Q.js.map +0 -1
  84. package/dist/schedule-tool-3FXRKJGN.js +0 -2
  85. package/dist/tool-4AO3ZMAY.js.map +0 -1
  86. package/dist/wiki-enrich-VEAYFVR2.js +0 -2
  87. /package/dist/{App-N2U77ED7.js.map → App-EU2AJWW5.js.map} +0 -0
  88. /package/dist/{ChatApp-GYVTECF6.js.map → ChatApp-ORR3U3AN.js.map} +0 -0
  89. /package/dist/{absorb-eval-WSAVWCZV.js.map → absorb-eval-3VGPDRWS.js.map} +0 -0
  90. /package/dist/{agent-SLRGXBMK.js.map → agent-NVJNOK5L.js.map} +0 -0
  91. /package/dist/{chunk-CZWEXRIE.js.map → chunk-3BMIZY6X.js.map} +0 -0
  92. /package/dist/{chunk-2GJFLPS7.js.map → chunk-5TFXFLMN.js.map} +0 -0
  93. /package/dist/{chunk-LVQHNTXV.js.map → chunk-5YAUENDI.js.map} +0 -0
  94. /package/dist/{chunk-DFWPTNZ5.js.map → chunk-7O7VDA3J.js.map} +0 -0
  95. /package/dist/{chunk-SVNYI6GR.js.map → chunk-DTWBB7B7.js.map} +0 -0
  96. /package/dist/{chunk-VYLMC5DO.js.map → chunk-GECGRCYC.js.map} +0 -0
  97. /package/dist/{chunk-UNZRZOED.js.map → chunk-J723FL3J.js.map} +0 -0
  98. /package/dist/{chunk-SFUNL7RV.js.map → chunk-K3QDK4BX.js.map} +0 -0
  99. /package/dist/{chunk-M7527M7D.js.map → chunk-MMBFAVBR.js.map} +0 -0
  100. /package/dist/{chunk-45TKVOJX.js.map → chunk-O7ZJS33Z.js.map} +0 -0
  101. /package/dist/{chunk-MXWAREAQ.js.map → chunk-OEB6RTRA.js.map} +0 -0
  102. /package/dist/{chunk-4JHMV3D3.js.map → chunk-OT5KLHUT.js.map} +0 -0
  103. /package/dist/{chunk-QI4FYJGJ.js.map → chunk-QNS3WHGU.js.map} +0 -0
  104. /package/dist/{chunk-EX4AREN5.js.map → chunk-SK24JFEK.js.map} +0 -0
  105. /package/dist/{chunk-BAO77R4L.js.map → chunk-TYONASHA.js.map} +0 -0
  106. /package/dist/{chunk-R5VGRKUW.js.map → chunk-TZVJP4H3.js.map} +0 -0
  107. /package/dist/{chunk-Q73QQPDB.js.map → chunk-UFX6INNI.js.map} +0 -0
  108. /package/dist/{chunk-JGX5IWNX.js.map → chunk-USTNT7P7.js.map} +0 -0
  109. /package/dist/{chunk-UII54DAP.js.map → chunk-UTYNYG7M.js.map} +0 -0
  110. /package/dist/{chunk-RV4WJZW5.js.map → chunk-UVJLIHLL.js.map} +0 -0
  111. /package/dist/{chunk-RGBQULXX.js.map → chunk-UYLVSS6I.js.map} +0 -0
  112. /package/dist/{chunk-GOAMSJ2D.js.map → chunk-WCOT35YG.js.map} +0 -0
  113. /package/dist/{client-B7FXDTYK.js.map → client-6KZZKCN2.js.map} +0 -0
  114. /package/dist/{config-MLP33NWR.js.map → config-W6JNVPBY.js.map} +0 -0
  115. /package/dist/{config-mutate-XQRUAVEH.js.map → config-mutate-57YT7BNB.js.map} +0 -0
  116. /package/dist/{config-mutator-5JFTMQ43.js.map → config-mutator-6NWQPE7K.js.map} +0 -0
  117. /package/dist/{contributions-ESUSYUQG.js.map → contributions-Y6B6LG7X.js.map} +0 -0
  118. /package/dist/{doctor-DIYZGSIS.js.map → doctor-ZP4KADAD.js.map} +0 -0
  119. /package/dist/{follow-up-tool-QXEYEWX7.js.map → follow-up-tool-5AMZKVI4.js.map} +0 -0
  120. /package/dist/{grants-MM7U6GCK.js.map → grants-O7SJ2J4B.js.map} +0 -0
  121. /package/dist/{hub-OC7PH2AR.js.map → hub-BZF3ZYQ5.js.map} +0 -0
  122. /package/dist/{promote-SIC6RWCX.js.map → promote-IJANZNQK.js.map} +0 -0
  123. /package/dist/{query-OP2MSR2G.js.map → query-DC74NB3R.js.map} +0 -0
  124. /package/dist/{query-settings-67332F5V.js.map → query-settings-RXFOATOZ.js.map} +0 -0
  125. /package/dist/{registry-G2ZG5TIN.js.map → registry-24IXRDWX.js.map} +0 -0
  126. /package/dist/{request-planner-THTPE3FP.js.map → request-planner-33CWWCJU.js.map} +0 -0
  127. /package/dist/{review-candidates-7PS7CHXF.js.map → review-candidates-ENWB6LHD.js.map} +0 -0
  128. /package/dist/{routing-PE7DB7WA.js.map → routing-AUFJ4MNP.js.map} +0 -0
  129. /package/dist/{schedule-tool-3FXRKJGN.js.map → schedule-tool-NAMOBMZE.js.map} +0 -0
  130. /package/dist/{scheduler-YTXCIQTZ.js.map → scheduler-KWSBBZKW.js.map} +0 -0
  131. /package/dist/{seat-6DMK4274.js.map → seat-YGMLJ6KS.js.map} +0 -0
  132. /package/dist/{select-CLDYPAOS.js.map → select-JJGBM6ZT.js.map} +0 -0
  133. /package/dist/{set-enabled-ZH2DH4GU.js.map → set-enabled-THE7QIGQ.js.map} +0 -0
  134. /package/dist/{tool-MKDTKBJ4.js.map → tool-4ACTSFKC.js.map} +0 -0
  135. /package/dist/{wiki-CH2HYJVI.js.map → wiki-YAW7UEOQ.js.map} +0 -0
  136. /package/dist/{wiki-enrich-VEAYFVR2.js.map → wiki-enrich-6ANFA2VB.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{c as O,d as v,e as R,f as E}from"./chunk-VY7TBMJU.js";import{existsSync as V,mkdirSync as z,readdirSync as M,readFileSync as G,renameSync as Y,writeFileSync as H}from"fs";import{resolve as K}from"path";function L(e){return e?.kind==="retro"||e?.kind==="retro-check"}var N={keep:"Keep it",loosen:"Loosen it",remove:"Remove it"};function T(e,r,n){let t=`guard rule \`${e.ruleId}\` in \`${e.file}\``,i=[`This was a monthly review of ${t}, added by the retro on run ${e.taskId}. It fires often on runs that went well.`];return!(r.status==="decided"&&r.verdict==="yes")||r.choice===N.keep||!r.choice?(i.push("Change nothing: the rule stays as it is."),i):(i.push(r.choice===N.remove?`The operator chose to remove it. Delete ${t} as a pull request.`:`The operator chose to loosen it. Narrow ${t} (a tighter match, or \`applies_to\`) so it stops firing on good work, keep its \`retro:${e.taskId}\` tag, and open it as a pull request.`),n&&i.push("The operator's note:",n),i.push("Do not change the live policy directly: the operator reviews the pull request first."),i)}function C(e){return e.status==="decided"&&e.verdict==="yes"&&!!e.choice&&e.choice!==$}function q(e,r,n){let t=[`This was a retro card about run ${e.taskId} (\`agentx trace show ${e.taskId}\`).`];if(!C(r))return t.push("Change nothing. Do not propose these fixes again on your own."),t;t.push(`The operator picked this fix: ${r.choice}`);let i=e.specs?.[(r.choices??[]).indexOf(r.choice)];return i&&t.push("Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):",i),n&&t.push("The operator's note on the fix:",n),t.push("Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.","Do not apply it to a live system directly. Tag what you add with `retro:"+e.taskId+"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list."),t}var $="None of these";function A(e,r){let n=e.list?` in the "${e.list}" list`:"",t=[`This card came from the operator's reminder "${e.title}"${n} (id ${e.id}).`];return t.push(r?`Do what the operator chose, then tick the reminder off: remindctl complete ${e.id}`:"Leave the reminder open; it will come back at a later check-in."),t}var u={title:120,ask:300,answers:3},b=["resurface","bring-back","weekly","cleanup"],k={perDay:5,resurface:3};function F(e){return e.title.length>u.title?`title is longer than ${u.title} characters`:e.ask.length>u.ask?`ask is longer than ${u.ask} characters`:(e.ask.match(/\?/g)??[]).length>1?"ask holds more than one question: one card asks one thing":(e.choices?.length??0)>u.answers?`more than ${u.answers} choices`:null}function ie(e,r){return e.length>u.title?`title is longer than ${u.title} characters`:r.length>u.ask?`message is longer than ${u.ask} characters`:null}function U(e){let r=new Date(e);return r.setHours(0,0,0,0),r.getTime()}function B(e,r,n){let t=U(n),i=e.filter(o=>o.followup&&Date.parse(o.created_at)>=t);return i.length>=k.perDay?`the follow-up screen budget is used up today (${k.perDay} cards): raise it again tomorrow`:r==="resurface"&&i.filter(o=>o.followup==="resurface").length>=k.resurface?`${k.resurface} resurface cards were already raised today: raise it again tomorrow`:null}function oe(e,r){return[`[screen gate] Your card ${e.id} ("${e.title}") was not shown to the owner: ${r}.`,"It is still in his inbox, unchanged. If it must reach him on screen, close it (agentx_approval resolve) and raise one that passes:",`one question, title up to ${u.title} characters, ask up to ${u.ask}, at most ${u.answers} choices.`].join(" ")}var P=["discard","keep","pause"];function I(e){return e==="approve"?"keep":P.includes(e)?e:null}var l={title:120,ask:300,recommend:300,source:500,note:500,resolution:300,pendingPerAgent:25},J={defaultExpiryDays:3,maxExpiryDays:30};function S(e){return K(e,".agentx","approvals")}var Q=/^[a-z0-9][a-z0-9-]{0,80}$/;function W(e){return Q.test(e)}function j(e,r){if(!W(r))throw new Error(`invalid card id: ${r}`);return K(S(e),`${r}.json`)}function X(e,r){let n=new Date(e).toISOString().slice(0,10),t=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${n}-${t||"card"}-${Math.random().toString(36).slice(2,6)}`}function g(e,r){z(S(e),{recursive:!0});let n=j(e,r.id),t=`${n}.${process.pid}.tmp`;H(t,JSON.stringify(r,null,2)+`
2
- `),Y(t,n)}function y(e,r){if(!W(r))return null;try{let n=JSON.parse(G(j(e,r),"utf-8")),t=n.if_silent==="approve"||n.outcome==="approve";return{...n,if_silent:I(n.if_silent)??"keep",...n.outcome?{outcome:I(n.outcome)??"keep"}:{},...t?{if_silent_asked:"approve"}:{}}}catch{return null}}function w(e,r){let n=S(e);if(!V(n))return[];let t=[];for(let i of M(n).filter(o=>o.endsWith(".json")&&!o.startsWith("_")).sort()){let o=y(e,i.slice(0,-5));o&&(!r||o.status===r)&&t.push(o)}return t}function a(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function Z(e,r,n){let t=r+n.maxExpiryDays*864e5,i,o=a(e);if(!o)i=r+n.defaultExpiryDays*864e5;else{let s=/^(\d+)\s*([hd])$/i.exec(o);if(s)i=r+Number(s[1])*(s[2].toLowerCase()==="d"?864e5:36e5);else if(i=Date.parse(o),Number.isNaN(i))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${o}")`}}return i<=r?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(i,t)).toISOString()}}function ee(e,r={}){let n=r.now??Date.now(),t=r.settings??J,i=a(e.title),o=a(e.ask),s=a(e.recommend),d=a(e.raised_by);if(!i)return{ok:!1,error:"title is required"};if(!o)return{ok:!1,error:"ask is required: the yes/no question"};if(!s)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!d)return{ok:!1,error:"raised_by is required: the agent id"};if(i.length>l.title)return{ok:!1,error:`title is longer than ${l.title} characters`};if(o.length>l.ask)return{ok:!1,error:`ask is longer than ${l.ask} characters`};if(s.length>l.recommend)return{ok:!1,error:`recommend is longer than ${l.recommend} characters`};let c=a(e.if_silent).toLowerCase(),D=I(c);if(!D)return{ok:!1,error:`if_silent must be one of ${P.join(", ")}`};let m=Z(e.expires,n,t);if(!m.ok)return m;let p=a(e.source);if(p.length>l.source)return{ok:!1,error:`source is longer than ${l.source} characters`};if(p&&/^[a-z][a-z0-9+.-]*:/i.test(p)&&!/^https?:\/\//i.test(p))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let x=O(e);if(!x.ok)return x;let h=a(e.followup).toLowerCase();if(h&&!b.includes(h))return{ok:!1,error:`followup must be one of ${b.join(", ")}`};let _,f=e.reply;return f&&typeof f=="object"&&a(f.channel)&&a(f.chatId)&&(_={channel:a(f.channel),chatId:a(f.chatId),...a(f.accountId)?{accountId:a(f.accountId)}:{}}),{ok:!0,card:{id:X(n,i),title:i,ask:o,recommend:s,if_silent:D,...c==="approve"?{if_silent_asked:"approve"}:{},expires:m.at,...p?{source:p}:{},raised_by:d,...r.node?{node:r.node}:{},created_at:new Date(n).toISOString(),..._?{reply:_}:{},...x.value,...r.origin?{origin:r.origin}:{},...h?{followup:h}:{},status:"pending"}}}function fe(e,r,n={}){let t=ee(r,n);if(!t.ok)return t;let i=F(t.card);if(i)return{ok:!1,error:i};if(t.card.followup){let c=B(w(e),t.card.followup,n.now??Date.now());if(c)return{ok:!1,error:c}}let o=c=>L(c.origin),s=o(t.card),d=w(e,"pending").filter(c=>c.raised_by===t.card.raised_by&&o(c)===s).length;if(d>=l.pendingPerAgent){let c=s?"retro cards":"cards";return{ok:!1,error:`${t.card.raised_by} already has ${d} ${c} waiting; wait for decisions before raising more`}}return g(e,t.card),t}function pe(e,r,n,t={}){let i=y(e,r);if(!i)return{ok:!1,error:`no card "${r}"`};if(i.status!=="pending")return{ok:!1,error:`card "${r}" is already ${i.status}`};let o=R(i,n,t);if(!o.ok)return o;let s=a(t.note).slice(0,l.note),d={...i,status:"decided",verdict:n,decided_by:t.by??"operator",decided_at:new Date(t.now??Date.now()).toISOString(),...s?{note:s}:{},...o.choice?{choice:o.choice}:{},...o.text?{text:o.text}:{}};return g(e,d),{ok:!0,card:d}}var re=new Set([void 0,"reminder"]);function ge(e,r,n){let t=y(e,r);if(!t)return{ok:!1,status:404,error:`no card "${r}"`};if(t.raised_by!==n.by||(t.node??"")!==(n.node??""))return{ok:!1,status:403,error:`card "${r}" was raised by another agent`};if(!re.has(t.origin?.kind))return{ok:!1,status:409,error:`card "${r}" is answered by the operator only`};if(t.status!=="pending")return{ok:!1,status:409,error:`card "${r}" is already ${t.status}`};let i=a(n.reason);if(!i)return{ok:!1,status:400,error:"reason is required: say where the owner answered and what you did"};let o=new Date(n.now??Date.now()).toISOString(),s={...t,status:"resolved",decided_by:n.by,decided_at:o,resolution:i.slice(0,l.resolution),agent_notified_at:o};return g(e,s),{ok:!0,card:s}}function he(e,r=Date.now()){let n=[];for(let t of w(e,"pending")){if(Date.parse(t.expires)>r)continue;let i={...t,status:"expired",outcome:t.if_silent,decided_by:"expiry",decided_at:new Date(r).toISOString()};g(e,i),n.push(i)}return n}function ke(e){return w(e).filter(r=>r.status!=="pending"&&!r.agent_notified_at)}function we(e,r,n=Date.now()){let t=y(e,r);!t||t.agent_notified_at||g(e,{...t,agent_notified_at:new Date(n).toISOString()})}var te="A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.";function ye(e){let r=e.origin?.kind==="retro"?e.origin:void 0,n=e.status==="decided"?e.verdict==="yes"?r&&!C(e)?`The operator picked "${$}", which counts as NO.`:"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${e.outcome??e.if_silent}.`,t=[`[Approval result] Your decision card "${e.title}" (${e.id}) is closed.`,`Question: ${e.ask}`,n],i=e.origin?.kind==="retro-check"?e.origin:void 0;if(e.status==="decided"&&e.verdict==="yes"&&!r&&!i&&t.push(...E(e)),e.note&&t.push(`Operator note: ${e.note}`),e.status==="decided"&&e.verdict==="no"&&!r&&!i&&t.push(te),e.source&&t.push(`Source: ${e.source}`),e.origin?.kind==="reminder"&&t.push(...A(e.origin,e.status==="decided"&&e.verdict==="yes")),r||i){let o=c=>c.replace(/\s+/g," ").trim(),s=v(e.draft,e.choice),d=e.text&&o(e.text)!==o(s)?e.text:void 0;t.push(...r?q(r,e,d):T(i,e,d))}return e.reply&&t.push(`You raised it from ${e.reply.channel} chat ${e.reply.chatId}; reply there if the requester should know.`),e.node&&t.push(`The operator answered it on another machine; the card was forwarded from ${e.node}.`),t.push("Act on this result now. Do not raise the same card again."),t.join(`
3
- `)}export{L as a,N as b,C as c,$ as d,F as e,ie as f,oe as g,P as h,l as i,S as j,W as k,y as l,w as m,fe as n,pe as o,ge as p,he as q,ke as r,we as s,ye as t};
4
- //# sourceMappingURL=chunk-KV4ZA7FS.js.map
1
+ import{c as D,d as v,e as R,f as E}from"./chunk-VY7TBMJU.js";import{existsSync as U,mkdirSync as V,readdirSync as z,readFileSync as G,renameSync as Y,writeFileSync as H}from"fs";import{resolve as K}from"path";function L(e){return e?.kind==="retro"||e?.kind==="retro-check"}var N={keep:"Keep it",loosen:"Loosen it",remove:"Remove it"};function T(e,r,n){let t=`guard rule \`${e.ruleId}\` in \`${e.file}\``,i=[`This was a monthly review of ${t}, added by the retro on run ${e.taskId}. It fires often on runs that went well.`];return!(r.status==="decided"&&r.verdict==="yes")||r.choice===N.keep||!r.choice?(i.push("Change nothing: the rule stays as it is."),i):(i.push(r.choice===N.remove?`The operator chose to remove it. Delete ${t} as a pull request.`:`The operator chose to loosen it. Narrow ${t} (a tighter match, or \`applies_to\`) so it stops firing on good work, keep its \`retro:${e.taskId}\` tag, and open it as a pull request.`),n&&i.push("The operator's note:",n),i.push("Do not change the live policy directly: the operator reviews the pull request first."),i)}function C(e){return e.status==="decided"&&e.verdict==="yes"&&!!e.choice&&e.choice!==b}function q(e,r,n){let t=[`This was a retro card about run ${e.taskId} (\`agentx trace show ${e.taskId}\`).`];if(!C(r))return t.push("Change nothing. Do not propose these fixes again on your own."),t;t.push(`The operator picked this fix: ${r.choice}`);let i=e.specs?.[(r.choices??[]).indexOf(r.choice)];return i&&t.push("Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):",i),n&&t.push("The operator's note on the fix:",n),t.push("Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.","Do not apply it to a live system directly. Tag what you add with `retro:"+e.taskId+"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list."),t}var b="None of these";function A(e,r){let n=e.list?` in the "${e.list}" list`:"",t=[`This card came from the operator's reminder "${e.title}"${n} (id ${e.id}).`];return t.push(r?`Do what the operator chose, then tick the reminder off: remindctl complete ${e.id}`:"Leave the reminder open; it will come back at a later check-in."),t}var u={title:120,ask:300,answers:3},$=["resurface","bring-back","weekly","cleanup"],k={perDay:5,resurface:3};function F(e){return e.title.length>u.title?`title is longer than ${u.title} characters`:e.ask.length>u.ask?`ask is longer than ${u.ask} characters`:(e.ask.match(/\?/g)??[]).length>1?"ask holds more than one question: one card asks one thing":(e.choices?.length??0)>u.answers?`more than ${u.answers} choices`:null}function ie(e,r){return e.length>u.title?`title is longer than ${u.title} characters`:r.length>u.ask?`message is longer than ${u.ask} characters`:null}function M(e){let r=new Date(e);return r.setHours(0,0,0,0),r.getTime()}function B(e,r,n){let t=M(n),i=e.filter(o=>o.followup&&Date.parse(o.created_at)>=t);return i.length>=k.perDay?`the follow-up screen budget is used up today (${k.perDay} cards): raise it again tomorrow`:r==="resurface"&&i.filter(o=>o.followup==="resurface").length>=k.resurface?`${k.resurface} resurface cards were already raised today: raise it again tomorrow`:null}function oe(e,r){return[`[screen gate] Your card ${e.id} ("${e.title}") was not shown to the owner: ${r}.`,"It is still in his inbox, unchanged. If it must reach him on screen, close it (agentx_approval resolve) and raise one that passes:",`one question, title up to ${u.title} characters, ask up to ${u.ask}, at most ${u.answers} choices.`].join(" ")}var P=["discard","keep","pause"];function I(e){return e==="approve"?"keep":P.includes(e)?e:null}var l={title:120,ask:300,recommend:300,source:500,note:500,resolution:300,pendingPerAgent:25},J={defaultExpiryDays:3,maxExpiryDays:30};function S(e){return K(e,".agentx","approvals")}var Q=/^[a-z0-9][a-z0-9-]{0,80}$/;function W(e){return Q.test(e)}function j(e,r){if(!W(r))throw new Error(`invalid card id: ${r}`);return K(S(e),`${r}.json`)}function X(e,r){let n=new Date(e).toISOString().slice(0,10),t=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${n}-${t||"card"}-${Math.random().toString(36).slice(2,6)}`}function g(e,r){V(S(e),{recursive:!0});let n=j(e,r.id),t=`${n}.${process.pid}.tmp`;H(t,JSON.stringify(r,null,2)+`
2
+ `),Y(t,n)}function y(e,r){if(!W(r))return null;try{let n=JSON.parse(G(j(e,r),"utf-8")),t=n.if_silent==="approve"||n.outcome==="approve";return{...n,if_silent:I(n.if_silent)??"keep",...n.outcome?{outcome:I(n.outcome)??"keep"}:{},...t?{if_silent_asked:"approve"}:{}}}catch{return null}}function w(e,r){let n=S(e);if(!U(n))return[];let t=[];for(let i of z(n).filter(o=>o.endsWith(".json")&&!o.startsWith("_")).sort()){let o=y(e,i.slice(0,-5));o&&(!r||o.status===r)&&t.push(o)}return t}function a(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function Z(e,r,n){let t=r+n.maxExpiryDays*864e5,i,o=a(e);if(!o)i=r+n.defaultExpiryDays*864e5;else{let s=/^(\d+)\s*([hd])$/i.exec(o);if(s)i=r+Number(s[1])*(s[2].toLowerCase()==="d"?864e5:36e5);else if(i=Date.parse(o),Number.isNaN(i))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${o}")`}}return i<=r?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(i,t)).toISOString()}}function ee(e,r={}){let n=r.now??Date.now(),t=r.settings??J,i=a(e.title),o=a(e.ask),s=a(e.recommend),d=a(e.raised_by);if(!i)return{ok:!1,error:"title is required"};if(!o)return{ok:!1,error:"ask is required: the yes/no question"};if(!s)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!d)return{ok:!1,error:"raised_by is required: the agent id"};if(i.length>l.title)return{ok:!1,error:`title is longer than ${l.title} characters`};if(o.length>l.ask)return{ok:!1,error:`ask is longer than ${l.ask} characters`};if(s.length>l.recommend)return{ok:!1,error:`recommend is longer than ${l.recommend} characters`};let c=a(e.if_silent).toLowerCase(),O=I(c);if(!O)return{ok:!1,error:`if_silent must be one of ${P.join(", ")}`};let m=Z(e.expires,n,t);if(!m.ok)return m;let p=a(e.source);if(p.length>l.source)return{ok:!1,error:`source is longer than ${l.source} characters`};if(p&&/^[a-z][a-z0-9+.-]*:/i.test(p)&&!/^https?:\/\//i.test(p))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let x=D(e);if(!x.ok)return x;let h=a(e.followup).toLowerCase();if(h&&!$.includes(h))return{ok:!1,error:`followup must be one of ${$.join(", ")}`};let _,f=e.reply;return f&&typeof f=="object"&&a(f.channel)&&a(f.chatId)&&(_={channel:a(f.channel),chatId:a(f.chatId),...a(f.accountId)?{accountId:a(f.accountId)}:{}}),{ok:!0,card:{id:X(n,i),title:i,ask:o,recommend:s,if_silent:O,...c==="approve"?{if_silent_asked:"approve"}:{},expires:m.at,...p?{source:p}:{},raised_by:d,...r.node?{node:r.node}:{},created_at:new Date(n).toISOString(),..._?{reply:_}:{},...x.value,...r.origin?{origin:r.origin}:{},...h?{followup:h}:{},status:"pending"}}}function fe(e,r,n={}){let t=ee(r,n);if(!t.ok)return t;let i=F(t.card);if(i)return{ok:!1,error:i};if(t.card.followup){let c=B(w(e),t.card.followup,n.now??Date.now());if(c)return{ok:!1,error:c}}let o=c=>L(c.origin),s=o(t.card),d=w(e,"pending").filter(c=>c.raised_by===t.card.raised_by&&o(c)===s).length;if(d>=l.pendingPerAgent){let c=s?"retro cards":"cards";return{ok:!1,error:`${t.card.raised_by} already has ${d} ${c} waiting; wait for decisions before raising more`}}return g(e,t.card),t}function pe(e,r,n,t={}){let i=y(e,r);if(!i)return{ok:!1,error:`no card "${r}"`};if(i.status!=="pending")return{ok:!1,error:`card "${r}" is already ${i.status}`};let o=R(i,n,t);if(!o.ok)return o;let s=a(t.note).slice(0,l.note),d={...i,status:"decided",verdict:n,decided_by:t.by??"operator",decided_at:new Date(t.now??Date.now()).toISOString(),...s?{note:s}:{},...o.choice?{choice:o.choice}:{},...o.text?{text:o.text}:{}};return g(e,d),{ok:!0,card:d}}var re=new Set([void 0,"reminder"]);function ge(e,r,n){let t=y(e,r);if(!t)return{ok:!1,status:404,error:`no card "${r}"`};if(t.raised_by!==n.by||(t.node??"")!==(n.node??""))return{ok:!1,status:403,error:`card "${r}" was raised by another agent`};if(!re.has(t.origin?.kind))return{ok:!1,status:409,error:`card "${r}" is answered by the operator only`};if(t.status!=="pending")return{ok:!1,status:409,error:`card "${r}" is already ${t.status}`};let i=a(n.reason);if(!i)return{ok:!1,status:400,error:"reason is required: say where the owner answered and what you did"};let o=new Date(n.now??Date.now()).toISOString(),s={...t,status:"resolved",decided_by:n.by,decided_at:o,resolution:i.slice(0,l.resolution),agent_notified_at:o};return g(e,s),{ok:!0,card:s}}function he(e,r=Date.now()){let n=[];for(let t of w(e,"pending")){if(Date.parse(t.expires)>r)continue;let i={...t,status:"expired",outcome:t.if_silent,decided_by:"expiry",decided_at:new Date(r).toISOString()};g(e,i),n.push(i)}return n}function ke(e){return w(e).filter(r=>r.status!=="pending"&&!r.agent_notified_at)}function we(e,r,n=Date.now()){let t=y(e,r);!t||t.agent_notified_at||g(e,{...t,agent_notified_at:new Date(n).toISOString()})}var te="A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.";function ye(e){let r=e.origin?.kind==="retro"?e.origin:void 0,n=e.status==="decided"?e.verdict==="yes"?r&&!C(e)?`The operator picked "${b}", which counts as NO.`:"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${e.outcome??e.if_silent}.`,t=[`[Approval result] Your decision card "${e.title}" (${e.id}) is closed.`,`Question: ${e.ask}`,n],i=e.origin?.kind==="retro-check"?e.origin:void 0;if(e.status==="decided"&&e.verdict==="yes"&&!r&&!i&&t.push(...E(e)),e.note&&t.push(`Operator note: ${e.note}`),e.status==="decided"&&e.verdict==="no"&&!r&&!i&&t.push(te),e.source&&t.push(`Source: ${e.source}`),e.origin?.kind==="reminder"&&t.push(...A(e.origin,e.status==="decided"&&e.verdict==="yes")),r||i){let o=c=>c.replace(/\s+/g," ").trim(),s=v(e.draft,e.choice),d=e.text&&o(e.text)!==o(s)?e.text:void 0;t.push(...r?q(r,e,d):T(i,e,d))}return e.reply&&t.push(`You raised it from ${e.reply.channel} chat ${e.reply.chatId}; reply there if the requester should know.`),e.node&&t.push(`The operator answered it on another machine; the card was forwarded from ${e.node}.`),t.push("Act on this result now. Do not raise the same card again."),t.join(`
3
+ `)}export{L as a,N as b,C as c,b as d,F as e,ie as f,oe as g,P as h,l as i,S as j,W as k,y as l,w as m,fe as n,pe as o,ge as p,he as q,ke as r,we as s,ye as t};
4
+ //# sourceMappingURL=chunk-TJZGAKIB.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/approvals/cards.ts","../src/approvals/origin.ts","../src/approvals/screen-gate.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { answerLines, buildChoices, draftFor, resolveAnswer, type CardChoices } from \"./choices\"\nimport { isRetroOrigin, originLines, RETRO_NONE, retroApproved, retroCheckLines, retroLines, type CardOrigin } from \"./origin\"\nimport { cardRuleBreak, FOLLOWUP_KINDS, followupBudgetRefusal, type FollowupKind } from \"./screen-gate\"\n\n// --- Decision cards: what an agent asks the operator ---\n//\n// An agent that needs a yes/no from the operator writes a card instead of\n// asking in chat. A card says what it is, the question, what the agent\n// recommends, and what happens if nobody answers by `expires`. Nothing\n// waits forever: past `expires` the daemon applies `if_silent` (sweep.ts).\n//\n// Storage: one JSON file per card under `.agentx/approvals/`, written\n// atomically, like wiki proposals. The CLI, the dashboard and the daemon\n// are separate processes and all read the same files.\n//\n// Field names match the API (`if_silent`, `raised_by`), so a stored card is\n// exactly what `POST /approvals` accepted.\n\n// No card approves itself (#741): only the operator says yes. \"approve\",\n// which older agents and stored cards may still carry, is read as \"keep\".\nexport type IfSilent = \"discard\" | \"keep\" | \"pause\"\nexport const IF_SILENT_VALUES: readonly IfSilent[] = [\"discard\", \"keep\", \"pause\"]\n\nfunction asIfSilent(v: string): IfSilent | null {\n if (v === \"approve\") return \"keep\"\n return IF_SILENT_VALUES.includes(v as IfSilent) ? (v as IfSilent) : null\n}\n\n// \"resolved\": closed by the agent that raised it, because the owner gave the\n// same answer somewhere else (in chat, #909) and the agent already acted on\n// it. Not a verdict: nothing is approved or rejected by it.\nexport type CardStatus = \"pending\" | \"decided\" | \"expired\" | \"resolved\"\nexport type Verdict = \"yes\" | \"no\"\n\n/** Where the agent was asked, so the verdict can be taken back there. */\nexport interface ReplyTarget {\n channel: string\n chatId: string\n accountId?: string\n}\n\nexport interface DecisionCard extends CardChoices {\n id: string\n title: string\n ask: string\n recommend: string\n if_silent: IfSilent\n /** ISO time the default applies. Always set. */\n expires: string\n /** Link to the draft, PR or issue. */\n source?: string\n raised_by: string\n /** The mesh node the raising agent is on, when the card was forwarded\n * here from there (forward.ts, #668). Unset: this node. */\n node?: string\n created_at: string\n reply?: ReplyTarget\n status: CardStatus\n /** The operator's answer (status \"decided\"). */\n verdict?: Verdict\n /** What applied on expiry (status \"expired\"). */\n outcome?: IfSilent\n /** Set when the agent, or a card stored before #741, asked for\n * \"approve\" on expiry; `if_silent` then holds \"keep\". Kept so the\n * record still shows what was originally asked. */\n if_silent_asked?: \"approve\"\n decided_by?: string\n decided_at?: string\n note?: string\n /** The option the operator picked, when the card offered choices. */\n choice?: string\n /** The message the operator approved, after any edit. */\n text?: string\n /** Set once the raising agent has been told the result. */\n agent_notified_at?: string\n /** Why the raising agent closed it (status \"resolved\"). */\n resolution?: string\n /** What the card is about, when the daemon raised it (origin.ts). */\n origin?: CardOrigin\n /** A follow-up card (#394): counted in the daily screen budget. */\n followup?: FollowupKind\n}\n\nexport const CARD_LIMITS = {\n title: 120,\n ask: 300,\n recommend: 300,\n source: 500,\n note: 500,\n resolution: 300,\n /** Pending cards one agent may have open at a time. */\n pendingPerAgent: 25,\n} as const\n\nexport interface CardSettings {\n defaultExpiryDays: number\n maxExpiryDays: number\n}\n\nexport const DEFAULT_CARD_SETTINGS: CardSettings = { defaultExpiryDays: 3, maxExpiryDays: 30 }\n\nexport function approvalsDir(root: string): string {\n return resolve(root, \".agentx\", \"approvals\")\n}\n\nconst CARD_ID_RE = /^[a-z0-9][a-z0-9-]{0,80}$/\n\nexport function isValidCardId(id: string): boolean {\n return CARD_ID_RE.test(id)\n}\n\nfunction fileFor(root: string, id: string): string {\n if (!isValidCardId(id)) throw new Error(`invalid card id: ${id}`)\n return resolve(approvalsDir(root), `${id}.json`)\n}\n\nexport function newCardId(now: number, title: string): string {\n const day = new Date(now).toISOString().slice(0, 10)\n const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40)\n return `${day}-${slug || \"card\"}-${Math.random().toString(36).slice(2, 6)}`\n}\n\nexport function saveCard(root: string, card: DecisionCard): void {\n mkdirSync(approvalsDir(root), { recursive: true })\n const path = fileFor(root, card.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(card, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\nexport function readCard(root: string, id: string): DecisionCard | null {\n if (!isValidCardId(id)) return null\n try {\n const card = JSON.parse(readFileSync(fileFor(root, id), \"utf-8\")) as DecisionCard\n // A card that expired as \"approve\" before #741 is read as \"keep\" too, so\n // an agent not yet told never hears \"default applied: approve\".\n const legacy = (card.if_silent as string) === \"approve\" || (card.outcome as string) === \"approve\"\n return {\n ...card,\n if_silent: asIfSilent(card.if_silent) ?? \"keep\",\n ...(card.outcome ? { outcome: asIfSilent(card.outcome) ?? \"keep\" } : {}),\n ...(legacy ? { if_silent_asked: \"approve\" as const } : {}),\n }\n } catch {\n return null\n }\n}\n\n/** Cards, oldest first; only `status` ones when given. */\nexport function listCards(root: string, status?: CardStatus): DecisionCard[] {\n const dir = approvalsDir(root)\n if (!existsSync(dir)) return []\n const out: DecisionCard[] = []\n for (const f of readdirSync(dir).filter((f) => f.endsWith(\".json\") && !f.startsWith(\"_\")).sort()) {\n const c = readCard(root, f.slice(0, -5))\n if (c && (!status || c.status === status)) out.push(c)\n }\n return out\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/**\n * `expires` as given by an agent: an ISO date or time, or a relative\n * \"12h\" / \"3d\". Unset: the default. Always capped at maxExpiryDays, so a\n * card can't be parked for a year.\n */\nexport function resolveExpiry(input: unknown, now: number, settings: CardSettings): { ok: true; at: string } | { ok: false; error: string } {\n const max = now + settings.maxExpiryDays * 86_400_000\n let at: number\n const raw = oneLine(input)\n if (!raw) {\n at = now + settings.defaultExpiryDays * 86_400_000\n } else {\n const rel = /^(\\d+)\\s*([hd])$/i.exec(raw)\n if (rel) {\n at = now + Number(rel[1]) * (rel[2].toLowerCase() === \"d\" ? 86_400_000 : 3_600_000)\n } else {\n at = Date.parse(raw)\n if (Number.isNaN(at)) return { ok: false, error: `expires must be an ISO date or time, or like \"12h\" / \"3d\" (got \"${raw}\")` }\n }\n }\n if (at <= now) return { ok: false, error: \"expires must be in the future\" }\n return { ok: true, at: new Date(Math.min(at, max)).toISOString() }\n}\n\nexport interface CardInput {\n title?: unknown\n ask?: unknown\n recommend?: unknown\n if_silent?: unknown\n expires?: unknown\n source?: unknown\n raised_by?: unknown\n reply?: unknown\n choices?: unknown\n draft?: unknown\n say?: unknown\n context?: unknown\n followup?: unknown\n}\n\n/** Validate what an agent sent and build a pending card. Never saves. */\nexport interface BuildCardOptions {\n now?: number\n settings?: CardSettings\n origin?: CardOrigin\n /** The peer the card was forwarded from. The daemon sets it after\n * checking the name against its mesh peers; never taken as sent. */\n node?: string\n}\n\nexport function buildCard(\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const now = opts.now ?? Date.now()\n const settings = opts.settings ?? DEFAULT_CARD_SETTINGS\n const title = oneLine(input.title)\n const ask = oneLine(input.ask)\n const recommend = oneLine(input.recommend)\n const raisedBy = oneLine(input.raised_by)\n if (!title) return { ok: false, error: \"title is required\" }\n if (!ask) return { ok: false, error: \"ask is required: the yes/no question\" }\n if (!recommend) return { ok: false, error: \"recommend is required: your advice and why, in one line\" }\n if (!raisedBy) return { ok: false, error: \"raised_by is required: the agent id\" }\n if (title.length > CARD_LIMITS.title) return { ok: false, error: `title is longer than ${CARD_LIMITS.title} characters` }\n if (ask.length > CARD_LIMITS.ask) return { ok: false, error: `ask is longer than ${CARD_LIMITS.ask} characters` }\n if (recommend.length > CARD_LIMITS.recommend) return { ok: false, error: `recommend is longer than ${CARD_LIMITS.recommend} characters` }\n const ifSilentRaw = oneLine(input.if_silent).toLowerCase()\n const ifSilent = asIfSilent(ifSilentRaw)\n if (!ifSilent) {\n return { ok: false, error: `if_silent must be one of ${IF_SILENT_VALUES.join(\", \")}` }\n }\n const expiry = resolveExpiry(input.expires, now, settings)\n if (!expiry.ok) return expiry\n const source = oneLine(input.source)\n if (source.length > CARD_LIMITS.source) return { ok: false, error: `source is longer than ${CARD_LIMITS.source} characters` }\n if (source && /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^https?:\\/\\//i.test(source)) {\n return { ok: false, error: \"source must be an http(s) link or a plain reference\" }\n }\n const extras = buildChoices(input)\n if (!extras.ok) return extras\n const followup = oneLine(input.followup).toLowerCase()\n if (followup && !(FOLLOWUP_KINDS as readonly string[]).includes(followup)) {\n return { ok: false, error: `followup must be one of ${FOLLOWUP_KINDS.join(\", \")}` }\n }\n let reply: ReplyTarget | undefined\n const r = input.reply as Record<string, unknown> | undefined\n if (r && typeof r === \"object\" && oneLine(r.channel) && oneLine(r.chatId)) {\n reply = { channel: oneLine(r.channel), chatId: oneLine(r.chatId), ...(oneLine(r.accountId) ? { accountId: oneLine(r.accountId) } : {}) }\n }\n return {\n ok: true,\n card: {\n id: newCardId(now, title),\n title,\n ask,\n recommend,\n if_silent: ifSilent,\n ...(ifSilentRaw === \"approve\" ? { if_silent_asked: \"approve\" as const } : {}),\n expires: expiry.at,\n ...(source ? { source } : {}),\n raised_by: raisedBy,\n ...(opts.node ? { node: opts.node } : {}),\n created_at: new Date(now).toISOString(),\n ...(reply ? { reply } : {}),\n ...extras.value,\n // Set by the daemon only (check-ins), never from what an agent sent.\n ...(opts.origin ? { origin: opts.origin } : {}),\n ...(followup ? { followup: followup as FollowupKind } : {}),\n status: \"pending\",\n },\n }\n}\n\n/** Validate, enforce the per-agent cap, and save. */\nexport function createCard(\n root: string,\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const built = buildCard(input, opts)\n if (!built.ok) return built\n // The screen gate (#394): refused here, the reason goes back to the author.\n const broken = cardRuleBreak(built.card)\n if (broken) return { ok: false, error: broken }\n if (built.card.followup) {\n const full = followupBudgetRefusal(listCards(root), built.card.followup, opts.now ?? Date.now())\n if (full) return { ok: false, error: full }\n }\n // Retro cards are raised for an agent, not by it: they get their own\n // count, so they never use up the agent's room for its own cards.\n const isRetro = (c: { origin?: CardOrigin }) => isRetroOrigin(c.origin)\n const retro = isRetro(built.card)\n const open = listCards(root, \"pending\").filter((c) => c.raised_by === built.card.raised_by && isRetro(c) === retro).length\n if (open >= CARD_LIMITS.pendingPerAgent) {\n const what = retro ? \"retro cards\" : \"cards\"\n return { ok: false, error: `${built.card.raised_by} already has ${open} ${what} waiting; wait for decisions before raising more` }\n }\n saveCard(root, built.card)\n return built\n}\n\n/** Record the operator's answer. Refuses anything no longer pending. */\nexport function decideCard(\n root: string,\n id: string,\n verdict: Verdict,\n opts: { by?: string; note?: string; now?: number; choice?: string | number; text?: string } = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, error: `no card \"${id}\"` }\n if (card.status !== \"pending\") return { ok: false, error: `card \"${id}\" is already ${card.status}` }\n const answer = resolveAnswer(card, verdict, opts)\n if (!answer.ok) return answer\n const note = oneLine(opts.note).slice(0, CARD_LIMITS.note)\n const decided: DecisionCard = {\n ...card,\n status: \"decided\",\n verdict,\n decided_by: opts.by ?? \"operator\",\n decided_at: new Date(opts.now ?? Date.now()).toISOString(),\n ...(note ? { note } : {}),\n ...(answer.choice ? { choice: answer.choice } : {}),\n ...(answer.text ? { text: answer.text } : {}),\n }\n saveCard(root, decided)\n return { ok: true, card: decided }\n}\n\n/** Cards whose answer the daemon acts on itself (a workflow run, a plan\n * step, a retro): only the operator closes those. A reminder card is the\n * agent's own to act on, so it may close it like one it raised. */\nconst AGENT_RESOLVABLE_ORIGINS = new Set<string | undefined>([undefined, \"reminder\"])\n\n/**\n * The raising agent closes its own pending card: the owner gave the same\n * answer outside the card (in chat) and the agent has acted on it (#909).\n * The card leaves the inbox, so no check-in or popup asks again. It is not\n * a verdict, and the agent is not sent a result for it: it already knows.\n */\nexport function resolveCard(\n root: string,\n id: string,\n opts: { by: string; reason?: unknown; node?: string; now?: number },\n): { ok: true; card: DecisionCard } | { ok: false; status: 400 | 403 | 404 | 409; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, status: 404, error: `no card \"${id}\"` }\n if (card.raised_by !== opts.by || (card.node ?? \"\") !== (opts.node ?? \"\")) {\n return { ok: false, status: 403, error: `card \"${id}\" was raised by another agent` }\n }\n if (!AGENT_RESOLVABLE_ORIGINS.has(card.origin?.kind)) {\n return { ok: false, status: 409, error: `card \"${id}\" is answered by the operator only` }\n }\n if (card.status !== \"pending\") return { ok: false, status: 409, error: `card \"${id}\" is already ${card.status}` }\n const reason = oneLine(opts.reason)\n if (!reason) return { ok: false, status: 400, error: \"reason is required: say where the owner answered and what you did\" }\n const at = new Date(opts.now ?? Date.now()).toISOString()\n const resolved: DecisionCard = {\n ...card,\n status: \"resolved\",\n decided_by: opts.by,\n decided_at: at,\n resolution: reason.slice(0, CARD_LIMITS.resolution),\n agent_notified_at: at,\n }\n saveCard(root, resolved)\n return { ok: true, card: resolved }\n}\n\n/** Apply `if_silent` to every pending card past its expiry. */\nexport function expireCards(root: string, now: number = Date.now()): DecisionCard[] {\n const out: DecisionCard[] = []\n for (const card of listCards(root, \"pending\")) {\n if (Date.parse(card.expires) > now) continue\n const expired: DecisionCard = {\n ...card,\n status: \"expired\",\n outcome: card.if_silent,\n decided_by: \"expiry\",\n decided_at: new Date(now).toISOString(),\n }\n saveCard(root, expired)\n out.push(expired)\n }\n return out\n}\n\n/** Decided or expired cards whose agent hasn't been told yet. */\nexport function cardsAwaitingAgentNotice(root: string): DecisionCard[] {\n return listCards(root).filter((c) => c.status !== \"pending\" && !c.agent_notified_at)\n}\n\nexport function markAgentNotified(root: string, id: string, now: number = Date.now()): void {\n const card = readCard(root, id)\n if (!card || card.agent_notified_at) return\n saveCard(root, { ...card, agent_notified_at: new Date(now).toISOString() })\n}\n\nexport const NO_UNDO_LINE =\n \"A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.\"\n\n/** What the raising agent is told. Plain text, one short message. */\nexport function verdictMessage(card: DecisionCard): string {\n const retro = card.origin?.kind === \"retro\" ? card.origin : undefined\n const result = card.status === \"decided\"\n ? (card.verdict === \"yes\"\n ? (retro && !retroApproved(card) ? `The operator picked \"${RETRO_NONE}\", which counts as NO.` : \"The operator said YES.\")\n : \"The operator said NO.\")\n : `Nobody answered before it expired, so the default applied: ${card.outcome ?? card.if_silent}.`\n const lines = [\n `[Approval result] Your decision card \"${card.title}\" (${card.id}) is closed.`,\n `Question: ${card.ask}`,\n result,\n ]\n // A retro card's pick and spec go through retroLines, labelled as the\n // reviewer's proposal: never \"Approved text (send exactly this)\".\n const check = card.origin?.kind === \"retro-check\" ? card.origin : undefined\n if (card.status === \"decided\" && card.verdict === \"yes\" && !retro && !check) lines.push(...answerLines(card))\n if (card.note) lines.push(`Operator note: ${card.note}`)\n // A late no on something the owner already approved in chat must not\n // quietly undo work that is done (#909).\n if (card.status === \"decided\" && card.verdict === \"no\" && !retro && !check) lines.push(NO_UNDO_LINE)\n if (card.source) lines.push(`Source: ${card.source}`)\n if (card.origin?.kind === \"reminder\") lines.push(...originLines(card.origin, card.status === \"decided\" && card.verdict === \"yes\"))\n if (retro || check) {\n // Compare ignoring whitespace so a dashboard that only reflows the draft\n // does not resend the whole draft as the operator's note.\n const squash = (s: string) => s.replace(/\\s+/g, \" \").trim()\n const draft = draftFor(card.draft, card.choice)\n const edited = card.text && squash(card.text) !== squash(draft) ? card.text : undefined\n lines.push(...(retro ? retroLines(retro, card, edited) : retroCheckLines(check!, card, edited)))\n }\n if (card.reply) lines.push(`You raised it from ${card.reply.channel} chat ${card.reply.chatId}; reply there if the requester should know.`)\n if (card.node) lines.push(`The operator answered it on another machine; the card was forwarded from ${card.node}.`)\n lines.push(\"Act on this result now. Do not raise the same card again.\")\n return lines.join(\"\\n\")\n}\n","// --- Where a card came from, when the daemon raised it ---\n//\n// Agents raise most cards themselves. A check-in (checkin.ts) raises one on\n// an agent's behalf for an open Apple Reminder, and records the reminder\n// here so the agent that gets the answer knows what to act on and what to\n// tick off. Only the daemon sets it: POST /approvals and the agent tool\n// never pass it through.\n\nexport interface ReminderOrigin {\n kind: \"reminder\"\n /** The reminder's full id, as remindctl prints it. */\n id: string\n title: string\n list?: string\n}\n\n/** An open request that needs attention, shown as a card on the Mac\n * (popup-runner.ts). Never stored: the request is the record. */\nexport interface RequestOrigin {\n kind: \"request\"\n id: string\n}\n\n/** A retro card (src/retro): fixes to the agents' environment proposed\n * from one run that struggled. The answer goes back to the agent that ran\n * it, which builds the picked fix for a second review. */\nexport interface RetroOrigin {\n kind: \"retro\"\n /** The run the retro read. */\n taskId: string\n /** Failure signature (wiki/failure-candidates.ts), for one card per signature. */\n signature: string\n /** The reviewer's spec for each fix, in the order of the card's choices\n * (without \"None of these\"). Only the picked one reaches the agent. */\n specs?: string[]\n}\n\n/** A monthly review of a check a retro added (src/retro/checks.ts): a\n * guard rule tagged `retro:<taskId>` that fires often on runs that went\n * well. The answer goes back to the agent that built it, which keeps,\n * loosens or removes it for a second review. */\nexport interface RetroCheckOrigin {\n kind: \"retro-check\"\n /** The guard rule's id. */\n ruleId: string\n /** The run whose retro asked for the rule. */\n taskId: string\n /** The policy file that holds the rule, relative to the daemon's folder. */\n file: string\n}\n\n/** A step of a workflow run asks the owner (src/workflows, #788): an\n * owner.ask step, a person.message to approve, or a run's approval at\n * start. The answer resumes the run; the agent that started it is not\n * told separately, the run is. */\nexport interface WorkflowOrigin {\n kind: \"workflow\"\n runId: string\n nodeId: string\n}\n\n/** An agent proposed a reusable workflow (#788). Yes turns it on. */\nexport interface WorkflowProposalOrigin {\n kind: \"workflow-proposal\"\n workflowId: string\n}\n\n/** A step of a tracked plan the owner approves when the plan is made\n * (src/requests/plan-sweep.ts, #788). The plan check reads the answer\n * and acts on it; the agent is not sent a result turn. */\nexport interface PlanStepOrigin {\n kind: \"plan-step\"\n requestId: string\n step: number\n}\n\nexport type CardOrigin = ReminderOrigin | RequestOrigin | RetroOrigin | RetroCheckOrigin | PlanStepOrigin | WorkflowOrigin | WorkflowProposalOrigin\n\n/** Retro cards of either kind: raised for an agent, not by it. */\nexport function isRetroOrigin(origin: CardOrigin | undefined): origin is RetroOrigin | RetroCheckOrigin {\n return origin?.kind === \"retro\" || origin?.kind === \"retro-check\"\n}\n\n/** The choices on a check review card, in this order. */\nexport const CHECK_CHOICES = { keep: \"Keep it\", loosen: \"Loosen it\", remove: \"Remove it\" } as const\n\n/** Lines for the agent told the result of a check review card. Keep, NO\n * and silence all leave the rule as it is. */\nexport function retroCheckLines(\n origin: RetroCheckOrigin,\n card: { status: string; verdict?: string; choice?: string },\n edited?: string,\n): string[] {\n const rule = `guard rule \\`${origin.ruleId}\\` in \\`${origin.file}\\``\n const lines = [`This was a monthly review of ${rule}, added by the retro on run ${origin.taskId}. It fires often on runs that went well.`]\n const yes = card.status === \"decided\" && card.verdict === \"yes\"\n if (!yes || card.choice === CHECK_CHOICES.keep || !card.choice) {\n lines.push(\"Change nothing: the rule stays as it is.\")\n return lines\n }\n lines.push(card.choice === CHECK_CHOICES.remove\n ? `The operator chose to remove it. Delete ${rule} as a pull request.`\n : `The operator chose to loosen it. Narrow ${rule} (a tighter match, or \\`applies_to\\`) so it stops firing on good work, keep its \\`retro:${origin.taskId}\\` tag, and open it as a pull request.`)\n if (edited) lines.push(\"The operator's note:\", edited)\n lines.push(\"Do not change the live policy directly: the operator reviews the pull request first.\")\n return lines\n}\n\n/** True when the operator answered a retro card with something to build:\n * YES and a fix picked. YES on \"None of these\" counts as NO. */\nexport function retroApproved(card: { status: string; verdict?: string; choice?: string }): boolean {\n return card.status === \"decided\" && card.verdict === \"yes\" && !!card.choice && card.choice !== RETRO_NONE\n}\n\n/** Lines for the agent told the result of a retro card. Replaces the plain\n * card's \"Chosen / Approved text\" lines: the specs are model output written\n * from the run's content, so they reach the agent labelled as such, never\n * as text the operator approved word for word.\n * `edited` is the operator's text when they changed the suggested one. */\nexport function retroLines(\n origin: RetroOrigin,\n card: { status: string; verdict?: string; choice?: string; choices?: string[] },\n edited?: string,\n): string[] {\n const lines = [`This was a retro card about run ${origin.taskId} (\\`agentx trace show ${origin.taskId}\\`).`]\n if (!retroApproved(card)) {\n lines.push(\"Change nothing. Do not propose these fixes again on your own.\")\n return lines\n }\n lines.push(`The operator picked this fix: ${card.choice}`)\n const spec = origin.specs?.[(card.choices ?? []).indexOf(card.choice!)]\n if (spec) {\n lines.push(\n \"Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):\",\n spec,\n )\n }\n if (edited) lines.push(\"The operator's note on the fix:\", edited)\n lines.push(\n \"Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.\",\n \"Do not apply it to a live system directly. Tag what you add with `retro:\" + origin.taskId + \"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list.\",\n )\n return lines\n}\n\n/** The last choice on every retro card. */\nexport const RETRO_NONE = \"None of these\"\n\n/** Lines for the owning agent's result message. */\nexport function originLines(origin: ReminderOrigin, approved: boolean): string[] {\n const where = origin.list ? ` in the \"${origin.list}\" list` : \"\"\n const lines = [`This card came from the operator's reminder \"${origin.title}\"${where} (id ${origin.id}).`]\n lines.push(approved\n ? `Do what the operator chose, then tick the reminder off: remindctl complete ${origin.id}`\n : \"Leave the reminder open; it will come back at a later check-in.\")\n return lines\n}\n","// --- The screen gatekeeper (#394, plan section 1b) ---\n//\n// What the fleet puts on the owner's screen passes one check, by script,\n// no model:\n// - one question per card; a title and an ask short enough to read in\n// about ten seconds (title 120, ask 300 characters);\n// - at most 3 ready-made answers (a plain card has Yes, No, Not now);\n// - follow-up cards (resurface, bring-back, weekly, clean-up) share a\n// budget of 5 a day, at most 3 of them resurface cards.\n// A card that fails is returned to its author with the reason: refused\n// when it is written, or not shown and told when the popup comes to it.\n// Nothing here rewrites, removes or answers a card. The call and Focus\n// hold is notify/hold.ts; the popup window takes no focus (card-window.ts).\n\nexport const SCREEN_LIMITS = { title: 120, ask: 300, answers: 3 } as const\n\nexport const FOLLOWUP_KINDS = [\"resurface\", \"bring-back\", \"weekly\", \"cleanup\"] as const\nexport type FollowupKind = (typeof FOLLOWUP_KINDS)[number]\n\nexport const SCREEN_BUDGET = { perDay: 5, resurface: 3 } as const\n\n/** Why this card may not go on the owner's screen, or null. */\nexport function cardRuleBreak(card: { title: string; ask: string; choices?: string[] }): string | null {\n if (card.title.length > SCREEN_LIMITS.title) return `title is longer than ${SCREEN_LIMITS.title} characters`\n if (card.ask.length > SCREEN_LIMITS.ask) return `ask is longer than ${SCREEN_LIMITS.ask} characters`\n if ((card.ask.match(/\\?/g) ?? []).length > 1) return \"ask holds more than one question: one card asks one thing\"\n if ((card.choices?.length ?? 0) > SCREEN_LIMITS.answers) return `more than ${SCREEN_LIMITS.answers} choices`\n return null\n}\n\n/** Why an agent's `agentx notify` may not go on the owner's screen, or\n * null: the same ten-second rule, title 120 and message 300. */\nexport function noticeRuleBreak(title: string, message: string): string | null {\n if (title.length > SCREEN_LIMITS.title) return `title is longer than ${SCREEN_LIMITS.title} characters`\n if (message.length > SCREEN_LIMITS.ask) return `message is longer than ${SCREEN_LIMITS.ask} characters`\n return null\n}\n\n/** Local midnight before `now`: the budget's day. */\nfunction dayStart(now: number): number {\n const d = new Date(now)\n d.setHours(0, 0, 0, 0)\n return d.getTime()\n}\n\n/** Why a follow-up card of this kind cannot be raised today, or null.\n * `cards` is every card, of any status: an answered one was on screen too. */\nexport function followupBudgetRefusal(\n cards: Array<{ followup?: FollowupKind; created_at: string }>,\n kind: FollowupKind,\n now: number,\n): string | null {\n const from = dayStart(now)\n const today = cards.filter((c) => c.followup && Date.parse(c.created_at) >= from)\n if (today.length >= SCREEN_BUDGET.perDay) {\n return `the follow-up screen budget is used up today (${SCREEN_BUDGET.perDay} cards): raise it again tomorrow`\n }\n if (kind === \"resurface\" && today.filter((c) => c.followup === \"resurface\").length >= SCREEN_BUDGET.resurface) {\n return `${SCREEN_BUDGET.resurface} resurface cards were already raised today: raise it again tomorrow`\n }\n return null\n}\n\n/** What the author hears when the popup does not show its card. */\nexport function returnedText(card: { id: string; title: string }, reason: string): string {\n return [\n `[screen gate] Your card ${card.id} (\"${card.title}\") was not shown to the owner: ${reason}.`,\n \"It is still in his inbox, unchanged. If it must reach him on screen, close it (agentx_approval resolve) and raise one that passes:\",\n `one question, title up to ${SCREEN_LIMITS.title} characters, ask up to ${SCREEN_LIMITS.ask}, at most ${SCREEN_LIMITS.answers} choices.`,\n ].join(\" \")\n}\n"],"mappings":"6DAAA,OAAS,cAAAA,EAAY,aAAAC,EAAW,eAAAC,EAAa,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,MAAqB,KAC5F,OAAS,WAAAC,MAAe,OC8EjB,SAASC,EAAcC,EAA0E,CACtG,OAAOA,GAAQ,OAAS,SAAWA,GAAQ,OAAS,aACtD,CAGO,IAAMC,EAAgB,CAAE,KAAM,UAAW,OAAQ,YAAa,OAAQ,WAAY,EAIlF,SAASC,EACdF,EACAG,EACAC,EACU,CACV,IAAMC,EAAO,gBAAgBL,EAAO,iBAAiBA,EAAO,SACtDM,EAAQ,CAAC,gCAAgCD,gCAAmCL,EAAO,gDAAgD,EAEzI,MAAI,EADQG,EAAK,SAAW,WAAaA,EAAK,UAAY,QAC9CA,EAAK,SAAWF,EAAc,MAAQ,CAACE,EAAK,QACtDG,EAAM,KAAK,0CAA0C,EAC9CA,IAETA,EAAM,KAAKH,EAAK,SAAWF,EAAc,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Sync","renameSync","writeFileSync","resolve","isRetroOrigin","origin","CHECK_CHOICES","retroCheckLines","card","edited","rule","lines","retroApproved","RETRO_NONE","retroLines","spec","originLines","approved","where","SCREEN_LIMITS","FOLLOWUP_KINDS","SCREEN_BUDGET","cardRuleBreak","card","noticeRuleBreak","title","message","dayStart","now","d","followupBudgetRefusal","cards","kind","from","today","c","returnedText","reason","IF_SILENT_VALUES","asIfSilent","v","CARD_LIMITS","DEFAULT_CARD_SETTINGS","approvalsDir","root","resolve","CARD_ID_RE","isValidCardId","id","fileFor","newCardId","now","title","day","slug","saveCard","card","mkdirSync","path","tmp","writeFileSync","renameSync","readCard","readFileSync","legacy","listCards","status","dir","existsSync","out","f","readdirSync","c","oneLine","resolveExpiry","input","settings","max","at","raw","rel","buildCard","opts","ask","recommend","raisedBy","ifSilentRaw","ifSilent","expiry","source","extras","buildChoices","followup","FOLLOWUP_KINDS","reply","r","createCard","built","broken","cardRuleBreak","full","followupBudgetRefusal","isRetro","isRetroOrigin","retro","open","what","decideCard","verdict","answer","resolveAnswer","note","decided","AGENT_RESOLVABLE_ORIGINS","resolveCard","reason","resolved","expireCards","expired","cardsAwaitingAgentNotice","markAgentNotified","NO_UNDO_LINE","verdictMessage","result","retroApproved","RETRO_NONE","lines","check","answerLines","originLines","squash","s","draft","draftFor","edited","retroLines","retroCheckLines"]}
1
+ {"version":3,"sources":["../src/approvals/cards.ts","../src/approvals/origin.ts","../src/approvals/screen-gate.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { answerLines, buildChoices, draftFor, resolveAnswer, type CardChoices } from \"./choices\"\nimport { isRetroOrigin, originLines, RETRO_NONE, retroApproved, retroCheckLines, retroLines, type CardOrigin } from \"./origin\"\nimport { cardRuleBreak, FOLLOWUP_KINDS, followupBudgetRefusal, type FollowupKind } from \"./screen-gate\"\n\n// --- Decision cards: what an agent asks the operator ---\n//\n// An agent that needs a yes/no from the operator writes a card instead of\n// asking in chat. A card says what it is, the question, what the agent\n// recommends, and what happens if nobody answers by `expires`. Nothing\n// waits forever: past `expires` the daemon applies `if_silent` (sweep.ts).\n//\n// Storage: one JSON file per card under `.agentx/approvals/`, written\n// atomically, like wiki proposals. The CLI, the dashboard and the daemon\n// are separate processes and all read the same files.\n//\n// Field names match the API (`if_silent`, `raised_by`), so a stored card is\n// exactly what `POST /approvals` accepted.\n\n// No card approves itself (#741): only the operator says yes. \"approve\",\n// which older agents and stored cards may still carry, is read as \"keep\".\nexport type IfSilent = \"discard\" | \"keep\" | \"pause\"\nexport const IF_SILENT_VALUES: readonly IfSilent[] = [\"discard\", \"keep\", \"pause\"]\n\nfunction asIfSilent(v: string): IfSilent | null {\n if (v === \"approve\") return \"keep\"\n return IF_SILENT_VALUES.includes(v as IfSilent) ? (v as IfSilent) : null\n}\n\n// \"resolved\": closed by the agent that raised it, because the owner gave the\n// same answer somewhere else (in chat, #909) and the agent already acted on\n// it. Not a verdict: nothing is approved or rejected by it.\nexport type CardStatus = \"pending\" | \"decided\" | \"expired\" | \"resolved\"\nexport type Verdict = \"yes\" | \"no\"\n\n/** Where the agent was asked, so the verdict can be taken back there. */\nexport interface ReplyTarget {\n channel: string\n chatId: string\n accountId?: string\n}\n\nexport interface DecisionCard extends CardChoices {\n id: string\n title: string\n ask: string\n recommend: string\n if_silent: IfSilent\n /** ISO time the default applies. Always set. */\n expires: string\n /** Link to the draft, PR or issue. */\n source?: string\n raised_by: string\n /** The mesh node the raising agent is on, when the card was forwarded\n * here from there (forward.ts, #668). Unset: this node. */\n node?: string\n created_at: string\n reply?: ReplyTarget\n status: CardStatus\n /** The operator's answer (status \"decided\"). */\n verdict?: Verdict\n /** What applied on expiry (status \"expired\"). */\n outcome?: IfSilent\n /** Set when the agent, or a card stored before #741, asked for\n * \"approve\" on expiry; `if_silent` then holds \"keep\". Kept so the\n * record still shows what was originally asked. */\n if_silent_asked?: \"approve\"\n decided_by?: string\n decided_at?: string\n note?: string\n /** The option the operator picked, when the card offered choices. */\n choice?: string\n /** The message the operator approved, after any edit. */\n text?: string\n /** Set once the raising agent has been told the result. */\n agent_notified_at?: string\n /** Why the raising agent closed it (status \"resolved\"). */\n resolution?: string\n /** What the card is about, when the daemon raised it (origin.ts). */\n origin?: CardOrigin\n /** A follow-up card (#394): counted in the daily screen budget. */\n followup?: FollowupKind\n}\n\nexport const CARD_LIMITS = {\n title: 120,\n ask: 300,\n recommend: 300,\n source: 500,\n note: 500,\n resolution: 300,\n /** Pending cards one agent may have open at a time. */\n pendingPerAgent: 25,\n} as const\n\nexport interface CardSettings {\n defaultExpiryDays: number\n maxExpiryDays: number\n}\n\nexport const DEFAULT_CARD_SETTINGS: CardSettings = { defaultExpiryDays: 3, maxExpiryDays: 30 }\n\nexport function approvalsDir(root: string): string {\n return resolve(root, \".agentx\", \"approvals\")\n}\n\nconst CARD_ID_RE = /^[a-z0-9][a-z0-9-]{0,80}$/\n\nexport function isValidCardId(id: string): boolean {\n return CARD_ID_RE.test(id)\n}\n\nfunction fileFor(root: string, id: string): string {\n if (!isValidCardId(id)) throw new Error(`invalid card id: ${id}`)\n return resolve(approvalsDir(root), `${id}.json`)\n}\n\nexport function newCardId(now: number, title: string): string {\n const day = new Date(now).toISOString().slice(0, 10)\n const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40)\n return `${day}-${slug || \"card\"}-${Math.random().toString(36).slice(2, 6)}`\n}\n\nexport function saveCard(root: string, card: DecisionCard): void {\n mkdirSync(approvalsDir(root), { recursive: true })\n const path = fileFor(root, card.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(card, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\nexport function readCard(root: string, id: string): DecisionCard | null {\n if (!isValidCardId(id)) return null\n try {\n const card = JSON.parse(readFileSync(fileFor(root, id), \"utf-8\")) as DecisionCard\n // A card that expired as \"approve\" before #741 is read as \"keep\" too, so\n // an agent not yet told never hears \"default applied: approve\".\n const legacy = (card.if_silent as string) === \"approve\" || (card.outcome as string) === \"approve\"\n return {\n ...card,\n if_silent: asIfSilent(card.if_silent) ?? \"keep\",\n ...(card.outcome ? { outcome: asIfSilent(card.outcome) ?? \"keep\" } : {}),\n ...(legacy ? { if_silent_asked: \"approve\" as const } : {}),\n }\n } catch {\n return null\n }\n}\n\n/** Cards, oldest first; only `status` ones when given. */\nexport function listCards(root: string, status?: CardStatus): DecisionCard[] {\n const dir = approvalsDir(root)\n if (!existsSync(dir)) return []\n const out: DecisionCard[] = []\n for (const f of readdirSync(dir).filter((f) => f.endsWith(\".json\") && !f.startsWith(\"_\")).sort()) {\n const c = readCard(root, f.slice(0, -5))\n if (c && (!status || c.status === status)) out.push(c)\n }\n return out\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/**\n * `expires` as given by an agent: an ISO date or time, or a relative\n * \"12h\" / \"3d\". Unset: the default. Always capped at maxExpiryDays, so a\n * card can't be parked for a year.\n */\nexport function resolveExpiry(input: unknown, now: number, settings: CardSettings): { ok: true; at: string } | { ok: false; error: string } {\n const max = now + settings.maxExpiryDays * 86_400_000\n let at: number\n const raw = oneLine(input)\n if (!raw) {\n at = now + settings.defaultExpiryDays * 86_400_000\n } else {\n const rel = /^(\\d+)\\s*([hd])$/i.exec(raw)\n if (rel) {\n at = now + Number(rel[1]) * (rel[2].toLowerCase() === \"d\" ? 86_400_000 : 3_600_000)\n } else {\n at = Date.parse(raw)\n if (Number.isNaN(at)) return { ok: false, error: `expires must be an ISO date or time, or like \"12h\" / \"3d\" (got \"${raw}\")` }\n }\n }\n if (at <= now) return { ok: false, error: \"expires must be in the future\" }\n return { ok: true, at: new Date(Math.min(at, max)).toISOString() }\n}\n\nexport interface CardInput {\n title?: unknown\n ask?: unknown\n recommend?: unknown\n if_silent?: unknown\n expires?: unknown\n source?: unknown\n raised_by?: unknown\n reply?: unknown\n choices?: unknown\n draft?: unknown\n say?: unknown\n context?: unknown\n followup?: unknown\n}\n\n/** Validate what an agent sent and build a pending card. Never saves. */\nexport interface BuildCardOptions {\n now?: number\n settings?: CardSettings\n origin?: CardOrigin\n /** The peer the card was forwarded from. The daemon sets it after\n * checking the name against its mesh peers; never taken as sent. */\n node?: string\n}\n\nexport function buildCard(\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const now = opts.now ?? Date.now()\n const settings = opts.settings ?? DEFAULT_CARD_SETTINGS\n const title = oneLine(input.title)\n const ask = oneLine(input.ask)\n const recommend = oneLine(input.recommend)\n const raisedBy = oneLine(input.raised_by)\n if (!title) return { ok: false, error: \"title is required\" }\n if (!ask) return { ok: false, error: \"ask is required: the yes/no question\" }\n if (!recommend) return { ok: false, error: \"recommend is required: your advice and why, in one line\" }\n if (!raisedBy) return { ok: false, error: \"raised_by is required: the agent id\" }\n if (title.length > CARD_LIMITS.title) return { ok: false, error: `title is longer than ${CARD_LIMITS.title} characters` }\n if (ask.length > CARD_LIMITS.ask) return { ok: false, error: `ask is longer than ${CARD_LIMITS.ask} characters` }\n if (recommend.length > CARD_LIMITS.recommend) return { ok: false, error: `recommend is longer than ${CARD_LIMITS.recommend} characters` }\n const ifSilentRaw = oneLine(input.if_silent).toLowerCase()\n const ifSilent = asIfSilent(ifSilentRaw)\n if (!ifSilent) {\n return { ok: false, error: `if_silent must be one of ${IF_SILENT_VALUES.join(\", \")}` }\n }\n const expiry = resolveExpiry(input.expires, now, settings)\n if (!expiry.ok) return expiry\n const source = oneLine(input.source)\n if (source.length > CARD_LIMITS.source) return { ok: false, error: `source is longer than ${CARD_LIMITS.source} characters` }\n if (source && /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^https?:\\/\\//i.test(source)) {\n return { ok: false, error: \"source must be an http(s) link or a plain reference\" }\n }\n const extras = buildChoices(input)\n if (!extras.ok) return extras\n const followup = oneLine(input.followup).toLowerCase()\n if (followup && !(FOLLOWUP_KINDS as readonly string[]).includes(followup)) {\n return { ok: false, error: `followup must be one of ${FOLLOWUP_KINDS.join(\", \")}` }\n }\n let reply: ReplyTarget | undefined\n const r = input.reply as Record<string, unknown> | undefined\n if (r && typeof r === \"object\" && oneLine(r.channel) && oneLine(r.chatId)) {\n reply = { channel: oneLine(r.channel), chatId: oneLine(r.chatId), ...(oneLine(r.accountId) ? { accountId: oneLine(r.accountId) } : {}) }\n }\n return {\n ok: true,\n card: {\n id: newCardId(now, title),\n title,\n ask,\n recommend,\n if_silent: ifSilent,\n ...(ifSilentRaw === \"approve\" ? { if_silent_asked: \"approve\" as const } : {}),\n expires: expiry.at,\n ...(source ? { source } : {}),\n raised_by: raisedBy,\n ...(opts.node ? { node: opts.node } : {}),\n created_at: new Date(now).toISOString(),\n ...(reply ? { reply } : {}),\n ...extras.value,\n // Set by the daemon only (check-ins), never from what an agent sent.\n ...(opts.origin ? { origin: opts.origin } : {}),\n ...(followup ? { followup: followup as FollowupKind } : {}),\n status: \"pending\",\n },\n }\n}\n\n/** Validate, enforce the per-agent cap, and save. */\nexport function createCard(\n root: string,\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const built = buildCard(input, opts)\n if (!built.ok) return built\n // The screen gate (#394): refused here, the reason goes back to the author.\n const broken = cardRuleBreak(built.card)\n if (broken) return { ok: false, error: broken }\n if (built.card.followup) {\n const full = followupBudgetRefusal(listCards(root), built.card.followup, opts.now ?? Date.now())\n if (full) return { ok: false, error: full }\n }\n // Retro cards are raised for an agent, not by it: they get their own\n // count, so they never use up the agent's room for its own cards.\n const isRetro = (c: { origin?: CardOrigin }) => isRetroOrigin(c.origin)\n const retro = isRetro(built.card)\n const open = listCards(root, \"pending\").filter((c) => c.raised_by === built.card.raised_by && isRetro(c) === retro).length\n if (open >= CARD_LIMITS.pendingPerAgent) {\n const what = retro ? \"retro cards\" : \"cards\"\n return { ok: false, error: `${built.card.raised_by} already has ${open} ${what} waiting; wait for decisions before raising more` }\n }\n saveCard(root, built.card)\n return built\n}\n\n/** Record the operator's answer. Refuses anything no longer pending. */\nexport function decideCard(\n root: string,\n id: string,\n verdict: Verdict,\n opts: { by?: string; note?: string; now?: number; choice?: string | number; text?: string } = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, error: `no card \"${id}\"` }\n if (card.status !== \"pending\") return { ok: false, error: `card \"${id}\" is already ${card.status}` }\n const answer = resolveAnswer(card, verdict, opts)\n if (!answer.ok) return answer\n const note = oneLine(opts.note).slice(0, CARD_LIMITS.note)\n const decided: DecisionCard = {\n ...card,\n status: \"decided\",\n verdict,\n decided_by: opts.by ?? \"operator\",\n decided_at: new Date(opts.now ?? Date.now()).toISOString(),\n ...(note ? { note } : {}),\n ...(answer.choice ? { choice: answer.choice } : {}),\n ...(answer.text ? { text: answer.text } : {}),\n }\n saveCard(root, decided)\n return { ok: true, card: decided }\n}\n\n/** Cards whose answer the daemon acts on itself (a workflow run, a plan\n * step, a retro): only the operator closes those. A reminder card is the\n * agent's own to act on, so it may close it like one it raised. */\nconst AGENT_RESOLVABLE_ORIGINS = new Set<string | undefined>([undefined, \"reminder\"])\n\n/**\n * The raising agent closes its own pending card: the owner gave the same\n * answer outside the card (in chat) and the agent has acted on it (#909).\n * The card leaves the inbox, so no check-in or popup asks again. It is not\n * a verdict, and the agent is not sent a result for it: it already knows.\n */\nexport function resolveCard(\n root: string,\n id: string,\n opts: { by: string; reason?: unknown; node?: string; now?: number },\n): { ok: true; card: DecisionCard } | { ok: false; status: 400 | 403 | 404 | 409; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, status: 404, error: `no card \"${id}\"` }\n if (card.raised_by !== opts.by || (card.node ?? \"\") !== (opts.node ?? \"\")) {\n return { ok: false, status: 403, error: `card \"${id}\" was raised by another agent` }\n }\n if (!AGENT_RESOLVABLE_ORIGINS.has(card.origin?.kind)) {\n return { ok: false, status: 409, error: `card \"${id}\" is answered by the operator only` }\n }\n if (card.status !== \"pending\") return { ok: false, status: 409, error: `card \"${id}\" is already ${card.status}` }\n const reason = oneLine(opts.reason)\n if (!reason) return { ok: false, status: 400, error: \"reason is required: say where the owner answered and what you did\" }\n const at = new Date(opts.now ?? Date.now()).toISOString()\n const resolved: DecisionCard = {\n ...card,\n status: \"resolved\",\n decided_by: opts.by,\n decided_at: at,\n resolution: reason.slice(0, CARD_LIMITS.resolution),\n agent_notified_at: at,\n }\n saveCard(root, resolved)\n return { ok: true, card: resolved }\n}\n\n/** Apply `if_silent` to every pending card past its expiry. */\nexport function expireCards(root: string, now: number = Date.now()): DecisionCard[] {\n const out: DecisionCard[] = []\n for (const card of listCards(root, \"pending\")) {\n if (Date.parse(card.expires) > now) continue\n const expired: DecisionCard = {\n ...card,\n status: \"expired\",\n outcome: card.if_silent,\n decided_by: \"expiry\",\n decided_at: new Date(now).toISOString(),\n }\n saveCard(root, expired)\n out.push(expired)\n }\n return out\n}\n\n/** Decided or expired cards whose agent hasn't been told yet. */\nexport function cardsAwaitingAgentNotice(root: string): DecisionCard[] {\n return listCards(root).filter((c) => c.status !== \"pending\" && !c.agent_notified_at)\n}\n\nexport function markAgentNotified(root: string, id: string, now: number = Date.now()): void {\n const card = readCard(root, id)\n if (!card || card.agent_notified_at) return\n saveCard(root, { ...card, agent_notified_at: new Date(now).toISOString() })\n}\n\nexport const NO_UNDO_LINE =\n \"A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.\"\n\n/** What the raising agent is told. Plain text, one short message. */\nexport function verdictMessage(card: DecisionCard): string {\n const retro = card.origin?.kind === \"retro\" ? card.origin : undefined\n const result = card.status === \"decided\"\n ? (card.verdict === \"yes\"\n ? (retro && !retroApproved(card) ? `The operator picked \"${RETRO_NONE}\", which counts as NO.` : \"The operator said YES.\")\n : \"The operator said NO.\")\n : `Nobody answered before it expired, so the default applied: ${card.outcome ?? card.if_silent}.`\n const lines = [\n `[Approval result] Your decision card \"${card.title}\" (${card.id}) is closed.`,\n `Question: ${card.ask}`,\n result,\n ]\n // A retro card's pick and spec go through retroLines, labelled as the\n // reviewer's proposal: never \"Approved text (send exactly this)\".\n const check = card.origin?.kind === \"retro-check\" ? card.origin : undefined\n if (card.status === \"decided\" && card.verdict === \"yes\" && !retro && !check) lines.push(...answerLines(card))\n if (card.note) lines.push(`Operator note: ${card.note}`)\n // A late no on something the owner already approved in chat must not\n // quietly undo work that is done (#909).\n if (card.status === \"decided\" && card.verdict === \"no\" && !retro && !check) lines.push(NO_UNDO_LINE)\n if (card.source) lines.push(`Source: ${card.source}`)\n if (card.origin?.kind === \"reminder\") lines.push(...originLines(card.origin, card.status === \"decided\" && card.verdict === \"yes\"))\n if (retro || check) {\n // Compare ignoring whitespace so a dashboard that only reflows the draft\n // does not resend the whole draft as the operator's note.\n const squash = (s: string) => s.replace(/\\s+/g, \" \").trim()\n const draft = draftFor(card.draft, card.choice)\n const edited = card.text && squash(card.text) !== squash(draft) ? card.text : undefined\n lines.push(...(retro ? retroLines(retro, card, edited) : retroCheckLines(check!, card, edited)))\n }\n if (card.reply) lines.push(`You raised it from ${card.reply.channel} chat ${card.reply.chatId}; reply there if the requester should know.`)\n if (card.node) lines.push(`The operator answered it on another machine; the card was forwarded from ${card.node}.`)\n lines.push(\"Act on this result now. Do not raise the same card again.\")\n return lines.join(\"\\n\")\n}\n","// --- Where a card came from, when the daemon raised it ---\n//\n// Agents raise most cards themselves. A check-in (checkin.ts) raises one on\n// an agent's behalf for an open Apple Reminder, and records the reminder\n// here so the agent that gets the answer knows what to act on and what to\n// tick off. Only the daemon sets it: POST /approvals and the agent tool\n// never pass it through.\n\nexport interface ReminderOrigin {\n kind: \"reminder\"\n /** The reminder's full id, as remindctl prints it. */\n id: string\n title: string\n list?: string\n}\n\n/** An open request that needs attention, shown as a card on the Mac\n * (popup-runner.ts). Never stored: the request is the record. */\nexport interface RequestOrigin {\n kind: \"request\"\n id: string\n}\n\n/** A retro card (src/retro): fixes to the agents' environment proposed\n * from one run that struggled. The answer goes back to the agent that ran\n * it, which builds the picked fix for a second review. */\nexport interface RetroOrigin {\n kind: \"retro\"\n /** The run the retro read. */\n taskId: string\n /** Failure signature (wiki/failure-candidates.ts), for one card per signature. */\n signature: string\n /** The reviewer's spec for each fix, in the order of the card's choices\n * (without \"None of these\"). Only the picked one reaches the agent. */\n specs?: string[]\n}\n\n/** A monthly review of a check a retro added (src/retro/checks.ts): a\n * guard rule tagged `retro:<taskId>` that fires often on runs that went\n * well. The answer goes back to the agent that built it, which keeps,\n * loosens or removes it for a second review. */\nexport interface RetroCheckOrigin {\n kind: \"retro-check\"\n /** The guard rule's id. */\n ruleId: string\n /** The run whose retro asked for the rule. */\n taskId: string\n /** The policy file that holds the rule, relative to the daemon's folder. */\n file: string\n}\n\n/** A step of a workflow run asks the owner (src/workflows, #788): an\n * owner.ask step, a person.message to approve, or a run's approval at\n * start. The answer resumes the run; the agent that started it is not\n * told separately, the run is. */\nexport interface WorkflowOrigin {\n kind: \"workflow\"\n runId: string\n nodeId: string\n}\n\n/** An agent proposed a reusable workflow (#788). Yes turns it on. */\nexport interface WorkflowProposalOrigin {\n kind: \"workflow-proposal\"\n workflowId: string\n}\n\n/** A step of a tracked plan the owner approves when the plan is made\n * (src/requests/plan-sweep.ts, #788). The plan check reads the answer\n * and acts on it; the agent is not sent a result turn. */\nexport interface PlanStepOrigin {\n kind: \"plan-step\"\n requestId: string\n step: number\n}\n\n/** A pull request that changes core paths waits for the owner (merge\n * policy, #1047). YES approves that one commit; the policy reads the\n * answer and updates the PR's status. No agent is sent a result turn. */\nexport interface MergePolicyOrigin {\n kind: \"merge-policy\"\n repo: string\n pr: number\n sha: string\n}\n\nexport type CardOrigin = ReminderOrigin | RequestOrigin | RetroOrigin | RetroCheckOrigin | PlanStepOrigin | WorkflowOrigin | WorkflowProposalOrigin | MergePolicyOrigin\n\n/** Retro cards of either kind: raised for an agent, not by it. */\nexport function isRetroOrigin(origin: CardOrigin | undefined): origin is RetroOrigin | RetroCheckOrigin {\n return origin?.kind === \"retro\" || origin?.kind === \"retro-check\"\n}\n\n/** The choices on a check review card, in this order. */\nexport const CHECK_CHOICES = { keep: \"Keep it\", loosen: \"Loosen it\", remove: \"Remove it\" } as const\n\n/** Lines for the agent told the result of a check review card. Keep, NO\n * and silence all leave the rule as it is. */\nexport function retroCheckLines(\n origin: RetroCheckOrigin,\n card: { status: string; verdict?: string; choice?: string },\n edited?: string,\n): string[] {\n const rule = `guard rule \\`${origin.ruleId}\\` in \\`${origin.file}\\``\n const lines = [`This was a monthly review of ${rule}, added by the retro on run ${origin.taskId}. It fires often on runs that went well.`]\n const yes = card.status === \"decided\" && card.verdict === \"yes\"\n if (!yes || card.choice === CHECK_CHOICES.keep || !card.choice) {\n lines.push(\"Change nothing: the rule stays as it is.\")\n return lines\n }\n lines.push(card.choice === CHECK_CHOICES.remove\n ? `The operator chose to remove it. Delete ${rule} as a pull request.`\n : `The operator chose to loosen it. Narrow ${rule} (a tighter match, or \\`applies_to\\`) so it stops firing on good work, keep its \\`retro:${origin.taskId}\\` tag, and open it as a pull request.`)\n if (edited) lines.push(\"The operator's note:\", edited)\n lines.push(\"Do not change the live policy directly: the operator reviews the pull request first.\")\n return lines\n}\n\n/** True when the operator answered a retro card with something to build:\n * YES and a fix picked. YES on \"None of these\" counts as NO. */\nexport function retroApproved(card: { status: string; verdict?: string; choice?: string }): boolean {\n return card.status === \"decided\" && card.verdict === \"yes\" && !!card.choice && card.choice !== RETRO_NONE\n}\n\n/** Lines for the agent told the result of a retro card. Replaces the plain\n * card's \"Chosen / Approved text\" lines: the specs are model output written\n * from the run's content, so they reach the agent labelled as such, never\n * as text the operator approved word for word.\n * `edited` is the operator's text when they changed the suggested one. */\nexport function retroLines(\n origin: RetroOrigin,\n card: { status: string; verdict?: string; choice?: string; choices?: string[] },\n edited?: string,\n): string[] {\n const lines = [`This was a retro card about run ${origin.taskId} (\\`agentx trace show ${origin.taskId}\\`).`]\n if (!retroApproved(card)) {\n lines.push(\"Change nothing. Do not propose these fixes again on your own.\")\n return lines\n }\n lines.push(`The operator picked this fix: ${card.choice}`)\n const spec = origin.specs?.[(card.choices ?? []).indexOf(card.choice!)]\n if (spec) {\n lines.push(\n \"Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):\",\n spec,\n )\n }\n if (edited) lines.push(\"The operator's note on the fix:\", edited)\n lines.push(\n \"Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.\",\n \"Do not apply it to a live system directly. Tag what you add with `retro:\" + origin.taskId + \"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list.\",\n )\n return lines\n}\n\n/** The last choice on every retro card. */\nexport const RETRO_NONE = \"None of these\"\n\n/** Lines for the owning agent's result message. */\nexport function originLines(origin: ReminderOrigin, approved: boolean): string[] {\n const where = origin.list ? ` in the \"${origin.list}\" list` : \"\"\n const lines = [`This card came from the operator's reminder \"${origin.title}\"${where} (id ${origin.id}).`]\n lines.push(approved\n ? `Do what the operator chose, then tick the reminder off: remindctl complete ${origin.id}`\n : \"Leave the reminder open; it will come back at a later check-in.\")\n return lines\n}\n","// --- The screen gatekeeper (#394, plan section 1b) ---\n//\n// What the fleet puts on the owner's screen passes one check, by script,\n// no model:\n// - one question per card; a title and an ask short enough to read in\n// about ten seconds (title 120, ask 300 characters);\n// - at most 3 ready-made answers (a plain card has Yes, No, Not now);\n// - follow-up cards (resurface, bring-back, weekly, clean-up) share a\n// budget of 5 a day, at most 3 of them resurface cards.\n// A card that fails is returned to its author with the reason: refused\n// when it is written, or not shown and told when the popup comes to it.\n// Nothing here rewrites, removes or answers a card. The call and Focus\n// hold is notify/hold.ts; the popup window takes no focus (card-window.ts).\n\nexport const SCREEN_LIMITS = { title: 120, ask: 300, answers: 3 } as const\n\nexport const FOLLOWUP_KINDS = [\"resurface\", \"bring-back\", \"weekly\", \"cleanup\"] as const\nexport type FollowupKind = (typeof FOLLOWUP_KINDS)[number]\n\nexport const SCREEN_BUDGET = { perDay: 5, resurface: 3 } as const\n\n/** Why this card may not go on the owner's screen, or null. */\nexport function cardRuleBreak(card: { title: string; ask: string; choices?: string[] }): string | null {\n if (card.title.length > SCREEN_LIMITS.title) return `title is longer than ${SCREEN_LIMITS.title} characters`\n if (card.ask.length > SCREEN_LIMITS.ask) return `ask is longer than ${SCREEN_LIMITS.ask} characters`\n if ((card.ask.match(/\\?/g) ?? []).length > 1) return \"ask holds more than one question: one card asks one thing\"\n if ((card.choices?.length ?? 0) > SCREEN_LIMITS.answers) return `more than ${SCREEN_LIMITS.answers} choices`\n return null\n}\n\n/** Why an agent's `agentx notify` may not go on the owner's screen, or\n * null: the same ten-second rule, title 120 and message 300. */\nexport function noticeRuleBreak(title: string, message: string): string | null {\n if (title.length > SCREEN_LIMITS.title) return `title is longer than ${SCREEN_LIMITS.title} characters`\n if (message.length > SCREEN_LIMITS.ask) return `message is longer than ${SCREEN_LIMITS.ask} characters`\n return null\n}\n\n/** Local midnight before `now`: the budget's day. */\nfunction dayStart(now: number): number {\n const d = new Date(now)\n d.setHours(0, 0, 0, 0)\n return d.getTime()\n}\n\n/** Why a follow-up card of this kind cannot be raised today, or null.\n * `cards` is every card, of any status: an answered one was on screen too. */\nexport function followupBudgetRefusal(\n cards: Array<{ followup?: FollowupKind; created_at: string }>,\n kind: FollowupKind,\n now: number,\n): string | null {\n const from = dayStart(now)\n const today = cards.filter((c) => c.followup && Date.parse(c.created_at) >= from)\n if (today.length >= SCREEN_BUDGET.perDay) {\n return `the follow-up screen budget is used up today (${SCREEN_BUDGET.perDay} cards): raise it again tomorrow`\n }\n if (kind === \"resurface\" && today.filter((c) => c.followup === \"resurface\").length >= SCREEN_BUDGET.resurface) {\n return `${SCREEN_BUDGET.resurface} resurface cards were already raised today: raise it again tomorrow`\n }\n return null\n}\n\n/** What the author hears when the popup does not show its card. */\nexport function returnedText(card: { id: string; title: string }, reason: string): string {\n return [\n `[screen gate] Your card ${card.id} (\"${card.title}\") was not shown to the owner: ${reason}.`,\n \"It is still in his inbox, unchanged. If it must reach him on screen, close it (agentx_approval resolve) and raise one that passes:\",\n `one question, title up to ${SCREEN_LIMITS.title} characters, ask up to ${SCREEN_LIMITS.ask}, at most ${SCREEN_LIMITS.answers} choices.`,\n ].join(\" \")\n}\n"],"mappings":"6DAAA,OAAS,cAAAA,EAAY,aAAAC,EAAW,eAAAC,EAAa,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,MAAqB,KAC5F,OAAS,WAAAC,MAAe,OCwFjB,SAASC,EAAcC,EAA0E,CACtG,OAAOA,GAAQ,OAAS,SAAWA,GAAQ,OAAS,aACtD,CAGO,IAAMC,EAAgB,CAAE,KAAM,UAAW,OAAQ,YAAa,OAAQ,WAAY,EAIlF,SAASC,EACdF,EACAG,EACAC,EACU,CACV,IAAMC,EAAO,gBAAgBL,EAAO,iBAAiBA,EAAO,SACtDM,EAAQ,CAAC,gCAAgCD,gCAAmCL,EAAO,gDAAgD,EAEzI,MAAI,EADQG,EAAK,SAAW,WAAaA,EAAK,UAAY,QAC9CA,EAAK,SAAWF,EAAc,MAAQ,CAACE,EAAK,QACtDG,EAAM,KAAK,0CAA0C,EAC9CA,IAETA,EAAM,KAAKH,EAAK,SAAWF,EAAc,OACrC,2CAA2CI,uBAC3C,2CAA2CA,4FAA+FL,EAAO,8CAA8C,EAC/LI,GAAQE,EAAM,KAAK,uBAAwBF,CAAM,EACrDE,EAAM,KAAK,sFAAsF,EAC1FA,EACT,CAIO,SAASC,EAAcJ,EAAsE,CAClG,OAAOA,EAAK,SAAW,WAAaA,EAAK,UAAY,OAAS,CAAC,CAACA,EAAK,QAAUA,EAAK,SAAWK,CACjG,CAOO,SAASC,EACdT,EACAG,EACAC,EACU,CACV,IAAME,EAAQ,CAAC,mCAAmCN,EAAO,+BAA+BA,EAAO,YAAY,EAC3G,GAAI,CAACO,EAAcJ,CAAI,EACrB,OAAAG,EAAM,KAAK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,GAAS,CAACuB,GAAOD,EAAM,KAAKL,EAAY,EAC/FjE,EAAK,QAAQsE,EAAM,KAAK,WAAWtE,EAAK,QAAQ,EAChDA,EAAK,QAAQ,OAAS,YAAYsE,EAAM,KAAK,GAAGG,EAAYzE,EAAK,OAAQA,EAAK,SAAW,WAAaA,EAAK,UAAY,KAAK,CAAC,EAC7HgD,GAASuB,EAAO,CAGlB,IAAMG,EAAUC,GAAcA,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EACpDC,EAAQC,EAAS7E,EAAK,MAAOA,EAAK,MAAM,EACxC8E,EAAS9E,EAAK,MAAQ0E,EAAO1E,EAAK,IAAI,IAAM0E,EAAOE,CAAK,EAAI5E,EAAK,KAAO,OAC9EsE,EAAM,KAAK,GAAItB,EAAQ+B,EAAW/B,EAAOhD,EAAM8E,CAAM,EAAIE,EAAgBT,EAAQvE,EAAM8E,CAAM,CAAE,EAEjG,OAAI9E,EAAK,OAAOsE,EAAM,KAAK,sBAAsBtE,EAAK,MAAM,gBAAgBA,EAAK,MAAM,mDAAmD,EACtIA,EAAK,MAAMsE,EAAM,KAAK,4EAA4EtE,EAAK,OAAO,EAClHsE,EAAM,KAAK,2DAA2D,EAC/DA,EAAM,KAAK;AAAA,CAAI,CACxB","names":["existsSync","mkdirSync","readdirSync","readFileSync","renameSync","writeFileSync","resolve","isRetroOrigin","origin","CHECK_CHOICES","retroCheckLines","card","edited","rule","lines","retroApproved","RETRO_NONE","retroLines","spec","originLines","approved","where","SCREEN_LIMITS","FOLLOWUP_KINDS","SCREEN_BUDGET","cardRuleBreak","card","noticeRuleBreak","title","message","dayStart","now","d","followupBudgetRefusal","cards","kind","from","today","c","returnedText","reason","IF_SILENT_VALUES","asIfSilent","v","CARD_LIMITS","DEFAULT_CARD_SETTINGS","approvalsDir","root","resolve","CARD_ID_RE","isValidCardId","id","fileFor","newCardId","now","title","day","slug","saveCard","card","mkdirSync","path","tmp","writeFileSync","renameSync","readCard","readFileSync","legacy","listCards","status","dir","existsSync","out","f","readdirSync","c","oneLine","resolveExpiry","input","settings","max","at","raw","rel","buildCard","opts","ask","recommend","raisedBy","ifSilentRaw","ifSilent","expiry","source","extras","buildChoices","followup","FOLLOWUP_KINDS","reply","r","createCard","built","broken","cardRuleBreak","full","followupBudgetRefusal","isRetro","isRetroOrigin","retro","open","what","decideCard","verdict","answer","resolveAnswer","note","decided","AGENT_RESOLVABLE_ORIGINS","resolveCard","reason","resolved","expireCards","expired","cardsAwaitingAgentNotice","markAgentNotified","NO_UNDO_LINE","verdictMessage","result","retroApproved","RETRO_NONE","lines","check","answerLines","originLines","squash","s","draft","draftFor","edited","retroLines","retroCheckLines"]}
@@ -1,4 +1,4 @@
1
- import{a as Re,b as w,c as z,d as Pe,e as ie,f as se,g as M,h as le,i as N,j as O,n as De,o as ze,p as _e,q as We}from"./chunk-XVTD6I34.js";import{e as Ee,i as Te}from"./chunk-QAWKN2N4.js";import{b as oe}from"./chunk-MTX4UPNB.js";import{a as G,b as Ce}from"./chunk-CZWEXRIE.js";import{c as Ie,d as ae,e as T,f as re,g as B}from"./chunk-B2QYMUTD.js";import{a as Se}from"./chunk-7LN4VKDU.js";import{a as Ae}from"./chunk-IMLAPB7G.js";import{b as $e}from"./chunk-MRIVENBY.js";import{l as ne,n as ke}from"./chunk-KV4ZA7FS.js";import{b as xe}from"./chunk-YMX3QCV7.js";import{c as ye,e as we}from"./chunk-LQE73AZR.js";import{G as K}from"./chunk-45TKVOJX.js";import{a as L,b as F}from"./chunk-SFUNL7RV.js";import{a as ve}from"./chunk-Q73QQPDB.js";import{a as be}from"./chunk-ROLSSYXE.js";import{Ha as ee,Ja as H,Ka as he,L as Z,M as me,Sa as te,T as dt,ia as fe,pa as ct}from"./chunk-DPIQCHXB.js";import{existsSync as j,readFileSync as Oe,writeFileSync as Ue,appendFileSync as ut,mkdirSync as mt}from"fs";import{dirname as ft,resolve as _}from"path";import{fileURLToPath as ht}from"url";import{hostname as bt}from"os";import{spawn as vt}from"child_process";function Me(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",a=`<header class="ax-topbar">
1
+ import{a as Re,b as w,c as z,d as Pe,e as ie,f as se,g as M,h as le,i as N,j as O,n as De,o as ze,p as _e,q as We}from"./chunk-XVTD6I34.js";import{e as Ee,i as Te}from"./chunk-QAWKN2N4.js";import{b as oe}from"./chunk-MTX4UPNB.js";import{a as G,b as Ce}from"./chunk-3BMIZY6X.js";import{c as Ie,d as ae,e as T,f as re,g as B}from"./chunk-B2QYMUTD.js";import{a as Se}from"./chunk-7LN4VKDU.js";import{a as Ae}from"./chunk-IMLAPB7G.js";import{b as $e}from"./chunk-MRIVENBY.js";import{l as ne,n as ke}from"./chunk-TJZGAKIB.js";import{b as xe}from"./chunk-YMX3QCV7.js";import{c as ye,e as we}from"./chunk-LQE73AZR.js";import{G as K}from"./chunk-O7ZJS33Z.js";import{a as L,b as F}from"./chunk-K3QDK4BX.js";import{a as ve}from"./chunk-UFX6INNI.js";import{a as be}from"./chunk-ROLSSYXE.js";import{Ia as ee,Ka as H,L as Z,La as he,M as me,T as dt,Ta as te,ia as fe,pa as ct}from"./chunk-IBK7AG4S.js";import{existsSync as j,readFileSync as Oe,writeFileSync as Ue,appendFileSync as ut,mkdirSync as mt}from"fs";import{dirname as ft,resolve as _}from"path";import{fileURLToPath as ht}from"url";import{hostname as bt}from"os";import{spawn as vt}from"child_process";function Me(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",a=`<header class="ax-topbar">
2
2
  <div class="ax-topbar__left">
3
3
  <div class="ax-brand">
4
4
  <span class="ax-brand__mark">AX</span>
@@ -858,4 +858,4 @@ tr:hover td { background: var(--bg-hover); }
858
858
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
859
859
  ${a}`).all(t,...n,...o).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function ga(e,t){return et(e,t,Z,"ORDER BY created_at")}function ua(e,t,n=50){return et(e,t,[...Z,...me],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}ct();var ue="member:",Yt=90,Vt="members",Xt="tailscale-user-login",Qt=400,Zt=60*60*1e3;function en(e){let t=e.scopes.find(n=>n.startsWith(ue));return t?t.slice(ue.length):null}function nt(e,t){if(!e)return null;let n=t.verify(e),a=n?en(n):null;return n&&a?{rec:n,personId:a}:null}function ya(e,t){let n=e.people().find(s=>s.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:a,record:o}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${ue}${n.id}`],expiresInDays:Yt}),{code:r,expiresAt:i}=e.codes.create({token:a,tokenId:o.id,name:n.id});return e.members.log({person:n.id,device:o.id,event:"invited"}),{ok:!0,code:r,expiresAt:i,tokenId:o.id,person:n}}var tn=Math.round(ye/6e4);function nn(e){return e==="client"?"Your project":"My work"}function wa(e){let t=nn(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${we(e.code)}`,` The code works once, for ${tn} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
860
860
  `)}var an="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",rn="Too many machines are waiting for the owner's answer. Try again later.",tt="That code didn't work. Check it, or ask the person who invited you for a new one.",at=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function rt(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function on(e){if(!rt(e))return null;let t=at(e,Xt).toLowerCase();return t?t.slice(0,80):null}function sn(e){let t=e.socket?.remoteAddress||"unknown";if(!rt(e))return t;let n=at(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function ln(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function dn(e){return e.identities.map(fe).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function ka(e,t){let n=Date.now(),a=t.now??Date.now,o=t.log??(b=>console.log(b)),r=sn(e),i=t.limiter.retryAfter(r);if(i>0)return o(`[member] pair-code refused from ${r}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,l="";try{let b=await xe(e,2048);s=b.code,l=ln(b.machine)}catch{}let c=t.codes.redeem(s),d=c?nt(c.token,t.tokens):null;if(await pn(n,t.minMs??Qt),!c||!d)return t.limiter.fail(r),o(`[member] pair-code failed from ${r}`),{status:401,body:{error:tt}};t.limiter.succeed(r);let{rec:m,personId:p}=d,k=t.people().find(b=>b.id===p);if(!k)return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:r,detail:"person no longer listed"}),o(`[member] pair-code for ${p} refused from ${r}: person no longer listed`),{status:403,body:{error:tt}};let u=on(e),f=dn(k);if(f.length&&(!u||!f.includes(u)))return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:r,detail:`network login ${u??"missing"}; expected ${f.join(" or ")}`}),o(`[member] ${p}: pairing from ${r} refused: the network says "${u??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:an}};let I=l||"Unnamed machine",x=k.name.slice(0,40),v=ke(t.root,{title:`New machine for ${x}`,ask:`From ${r}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${I}". Let it see ${x}'s own work?`,recommend:`Yes if ${x} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:Vt},{now:a()});return v.ok?(t.members.add({tokenId:m.id,personId:p,name:I,state:"pending",cardId:v.card.id,address:r,...u?{network:u}:{},createdAt:new Date(a()).toISOString()}),t.members.log({person:p,device:m.id,event:"paired",address:r,detail:I}),o(`[member] ${p} paired "${I}" from ${r}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:p,name:I,state:"pending"},token:c.token}):(t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:r,detail:v.error}),o(`[member] ${p}: pairing from ${r} refused: ${v.error}`),{status:503,body:{error:rn}})}var Q="this machine is not paired",cn="waiting for the owner to approve this machine";function ot(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function $a(e,t){return t.state==="pending"&&t.cardId?ot(ne(e,t.cardId)):null}function Aa(e,t,n){let a=t.now??Date.now,o=t.log??(d=>console.log(d)),r=nt(e,t.tokens);if(!r)return{ok:!1,status:401,error:Q};let{rec:i,personId:s}=r,l=t.members.byToken(i.id);if(!l||l.state==="removed"||l.personId!==s)return{ok:!1,status:401,error:Q};if(t.people&&!t.people().some(d=>d.id===s))return it(t,i.id,"person no longer listed"),o(`[member] ${s}: "${l.name}" ended: person no longer listed`),{ok:!1,status:401,error:Q};if(l.state==="pending"){let d=l.cardId?ne(t.root,l.cardId):null,m=ot(d);if(m==="yes")l=t.members.update(i.id,{state:"active",approvedAt:new Date(a()).toISOString()})??l,t.members.log({person:s,device:i.id,event:"approved",detail:d?.decided_by}),o(`[member] ${s}: "${l.name}" approved`);else if(m==="no"){let p=d?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(i.id),t.members.update(i.id,{state:"removed",removedAt:new Date(a()).toISOString(),removedReason:p}),t.members.log({person:s,device:i.id,event:"refused",detail:p}),o(`[member] ${s}: "${l.name}" refused: ${p}`),{ok:!1,status:401,error:Q}}else return{ok:!1,status:403,error:cn,waiting:!0}}let c=l.lastSeenAt?Date.parse(l.lastSeenAt):0;return n&&(a()-c>=Zt||l.lastAddress!==n)&&(l=t.members.update(i.id,{lastSeenAt:new Date(a()).toISOString(),lastAddress:n})??l,t.members.log({person:s,device:i.id,event:"signed-in",address:n})),{ok:!0,device:l,personId:s,rec:i}}function it(e,t,n="removed by the owner"){let a=e.members.byToken(t);if(!a)return null;e.tokens.revoke(t);let o=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:a.personId,device:t,event:"removed",detail:n}),o}function Sa(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>it(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function pn(e,t){let n=e+t-Date.now();n>0&&await new Promise(a=>setTimeout(a,n))}var st=["gitlab","github"];function gn(e,t,n){let a=String(t||"").trim().toLowerCase();if(!st.includes(a))throw new Error(`Request status works on ${st.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let o=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(r=>String(r).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...o,a])]:o.filter(r=>r!==a),`request status on ${a} is ${n?"on":"off"}`}function Ea(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function Ta(e){let{summary:t}=G(n=>gn(n,e?.channel,!!e?.enabled));return{summary:t}}function Pa(e){return new Set(Object.entries(e).filter(([,t])=>t?.wiki?.absorb?.enabled===!1).map(([t])=>t))}function Da(e,t){return t.only?{agents:[t.only],skipped:[]}:{agents:e.filter(n=>!t.off.has(n)),skipped:e.filter(n=>t.off.has(n))}}function za(e,t){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===t?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function _a(e,t){if(t){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var un="https://ntfy.sh";function Ma(e){return{enabled:!!e?.enabled,server:e?.server||un,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Na(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let a=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(a))throw new Error("ntfy server must be an http(s) URL");n.server=a}if("topic"in t){let a=String(t.topic).trim();if(!a)throw new Error("ntfy topic cannot be empty");n.topic=a}if("token"in t){let a=String(t.token??"").trim();a?n.token=a:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{Be as a,An as b,Sn as c,In as d,Pn as e,Dn as f,zn as g,pa as h,ga as i,ua as j,Yt as k,ya as l,tn as m,nn as n,wa as o,sn as p,ka as q,$a as r,Aa as s,it as t,Sa as u,st as v,gn as w,Ea as x,Ta as y,Pa as z,Da as A,za as B,_a as C,Ma as D,Na as E,Ht as F,ta as G,sa as H,la as I};
861
- //# sourceMappingURL=chunk-BAO77R4L.js.map
861
+ //# sourceMappingURL=chunk-TYONASHA.js.map
@@ -1,4 +1,4 @@
1
- import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{Ra as tt,Sa as nt}from"./chunk-DPIQCHXB.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
1
+ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{Sa as tt,Ta as nt}from"./chunk-IBK7AG4S.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
2
2
  ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
3
3
  INSERT INTO schema_version (v) VALUES (3);
4
4
  `)}function Ot(e){e.exec(`
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
111
111
  `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
112
  `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),cn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
113
  ${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
114
- //# sourceMappingURL=chunk-R5VGRKUW.js.map
114
+ //# sourceMappingURL=chunk-TZVJP4H3.js.map
@@ -1,4 +1,4 @@
1
- import{a as h}from"./chunk-RV4WJZW5.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-UVJLIHLL.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-Q73QQPDB.js.map
4
+ //# sourceMappingURL=chunk-UFX6INNI.js.map
@@ -1,2 +1,2 @@
1
- import{q as d}from"./chunk-3LAQ74H7.js";import{b as i,c as u,d as l,e as c}from"./chunk-SFUNL7RV.js";import f from"cronstrue";var p=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||p,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return f.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return d(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{p as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
2
- //# sourceMappingURL=chunk-JGX5IWNX.js.map
1
+ import{q as d}from"./chunk-MOCKFVYE.js";import{b as i,c as u,d as l,e as c}from"./chunk-K3QDK4BX.js";import f from"cronstrue";var p=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||p,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return f.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return d(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{p as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
2
+ //# sourceMappingURL=chunk-USTNT7P7.js.map
@@ -1,6 +1,6 @@
1
- import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-R5VGRKUW.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-TZVJP4H3.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
6
- //# sourceMappingURL=chunk-UII54DAP.js.map
6
+ //# sourceMappingURL=chunk-UTYNYG7M.js.map
@@ -1,4 +1,4 @@
1
- import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-UII54DAP.js";import{y as C,z as K}from"./chunk-R5VGRKUW.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
1
+ import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-UTYNYG7M.js";import{y as C,z as K}from"./chunk-TZVJP4H3.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
2
2
  `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
3
3
  `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
4
4
  `));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
@@ -102,4 +102,4 @@ We use GitLab for version control.
102
102
  There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
103
 
104
104
  ${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
105
- //# sourceMappingURL=chunk-RV4WJZW5.js.map
105
+ //# sourceMappingURL=chunk-UVJLIHLL.js.map