noskills 4.5.2 → 5.0.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 (223) hide show
  1. package/README.md +497 -18
  2. package/noskills.js +145 -1
  3. package/package.json +14 -1
  4. package/{chunks/ajan-bridge-BNPC757J.js → ts/chunks/ajan-bridge-6UUIUFAV.js} +1 -1
  5. package/ts/chunks/anthropic-ICVQ5GK6.js +1 -0
  6. package/ts/chunks/approve-R7MCYHCS.js +1 -0
  7. package/ts/chunks/ask-GBLFPNFX.js +2 -0
  8. package/ts/chunks/block-YEKLMXHR.js +1 -0
  9. package/ts/chunks/cancel-7NS4WM2N.js +1 -0
  10. package/ts/chunks/chunk-2CLD527I.js +1 -0
  11. package/ts/chunks/chunk-34AWV7DB.js +1 -0
  12. package/ts/chunks/chunk-3M26Y3NG.js +27 -0
  13. package/{chunks/chunk-J25XTDQQ.js → ts/chunks/chunk-3QVRJO3V.js} +1 -1
  14. package/ts/chunks/chunk-5ALJRBMW.js +22 -0
  15. package/ts/chunks/chunk-5NMDE2VZ.js +4 -0
  16. package/ts/chunks/chunk-6BKTY7SA.js +4 -0
  17. package/ts/chunks/chunk-6M7PCVUR.js +1 -0
  18. package/ts/chunks/chunk-6O2RXYTM.js +3 -0
  19. package/ts/chunks/chunk-7DIQYKPL.js +3 -0
  20. package/ts/chunks/chunk-7J6R2D2K.js +2 -0
  21. package/ts/chunks/chunk-AW3XJGEP.js +1 -0
  22. package/ts/chunks/chunk-BRC46A3N.js +39 -0
  23. package/ts/chunks/chunk-C5LYQDQH.js +368 -0
  24. package/ts/chunks/chunk-CCYWFSXR.js +3 -0
  25. package/{chunks/chunk-OAWYVETM.js → ts/chunks/chunk-CL55MNGD.js} +1 -1
  26. package/ts/chunks/chunk-CSP2GUD4.js +29 -0
  27. package/{chunks/chunk-EROZRDGT.js → ts/chunks/chunk-D2UKX2VW.js} +1 -1
  28. package/ts/chunks/chunk-DGYDUGTM.js +1 -0
  29. package/ts/chunks/chunk-FB3Z7XYQ.js +1 -0
  30. package/ts/chunks/chunk-FLLYK5FU.js +1 -0
  31. package/{chunks/chunk-EJYSOUEA.js → ts/chunks/chunk-GCPGG4YB.js} +1 -1
  32. package/{chunks/chunk-FYFUEK4U.js → ts/chunks/chunk-HLDPASM6.js} +1 -1
  33. package/ts/chunks/chunk-HNQA5O2S.js +2 -0
  34. package/ts/chunks/chunk-HUP7XWW6.js +1 -0
  35. package/ts/chunks/chunk-J3XNDEMU.js +4 -0
  36. package/ts/chunks/chunk-K6FVY52W.js +5 -0
  37. package/ts/chunks/chunk-KQJGXVWX.js +91 -0
  38. package/ts/chunks/chunk-M4U4Y3XQ.js +7 -0
  39. package/ts/chunks/chunk-M6CAJL36.js +1 -0
  40. package/ts/chunks/chunk-MPHTBN7E.js +1 -0
  41. package/ts/chunks/chunk-NYIFCLEG.js +1 -0
  42. package/ts/chunks/chunk-RRDWQKZY.js +1 -0
  43. package/ts/chunks/chunk-RVNSKPFL.js +1 -0
  44. package/ts/chunks/chunk-S5F2DAAG.js +5 -0
  45. package/ts/chunks/chunk-SCYP2G2T.js +3 -0
  46. package/ts/chunks/chunk-SWP6BJR6.js +147 -0
  47. package/{chunks/chunk-XDRX4ZBJ.js → ts/chunks/chunk-SWRVSRYY.js} +1 -1
  48. package/ts/chunks/chunk-T2X4E35X.js +1 -0
  49. package/ts/chunks/chunk-TDLTCTV4.js +1 -0
  50. package/ts/chunks/chunk-TKBGNLNV.js +1 -0
  51. package/ts/chunks/chunk-UY4YFVSW.js +3 -0
  52. package/ts/chunks/chunk-V5ZXCJPI.js +2 -0
  53. package/ts/chunks/chunk-W46BJM2F.js +1 -0
  54. package/ts/chunks/chunk-W7KQFMHV.js +1 -0
  55. package/ts/chunks/chunk-XGRZPTAD.js +24 -0
  56. package/ts/chunks/chunk-XTQFSF6C.js +1 -0
  57. package/ts/chunks/chunk-YN3SHWBR.js +1 -0
  58. package/ts/chunks/chunk-ZAY6LSJD.js +2 -0
  59. package/ts/chunks/chunk-ZGVXR3EC.js +8 -0
  60. package/ts/chunks/chunk-ZW5C5IGT.js +32 -0
  61. package/ts/chunks/claude-code-J2V5WSGZ.js +1 -0
  62. package/ts/chunks/concern-EDWQHU4H.js +1 -0
  63. package/ts/chunks/config-E7BDBHPK.js +1 -0
  64. package/ts/chunks/decision-ledger-5QXKZSV2.js +1 -0
  65. package/ts/chunks/delegate-LVQQ3GCV.js +1 -0
  66. package/ts/chunks/diagrams-2F5ZYXA7.js +1 -0
  67. package/ts/chunks/diagrams-H62JGTIS.js +1 -0
  68. package/ts/chunks/done-U3TOSZIX.js +1 -0
  69. package/ts/chunks/followup-J2HJU3ZT.js +1 -0
  70. package/ts/chunks/free-73WMLMCT.js +1 -0
  71. package/ts/chunks/gemini-GA6P4M7D.js +1 -0
  72. package/ts/chunks/init-6CVDGRY2.js +1 -0
  73. package/ts/chunks/invoke-hook-2TMKWL7I.js +15 -0
  74. package/ts/chunks/kiro-BJSKSAUC.js +1 -0
  75. package/ts/chunks/learn-7Q2VWZMI.js +7 -0
  76. package/ts/chunks/ledger-XR4AHZRX.js +2 -0
  77. package/ts/chunks/list-CUQCPXZH.js +1 -0
  78. package/ts/chunks/manager-WTLJ5C2I.js +3 -0
  79. package/ts/chunks/mod-BZA5TFW7.js +1 -0
  80. package/ts/chunks/mod-RWA5ZPYH.js +1 -0
  81. package/ts/chunks/mod-X372UNSQ.js +1 -0
  82. package/ts/chunks/mod-XVE4ZWPY.js +1 -0
  83. package/ts/chunks/next-CEYZSYGB.js +20 -0
  84. package/ts/chunks/node-33JV5VS3.js +15 -0
  85. package/ts/chunks/node-XYP2DQHR.js +74 -0
  86. package/{chunks/node-2XIHQ2M4.js → ts/chunks/node-ZSGIX7K3.js} +1 -1
  87. package/ts/chunks/ollama-X6OGN5BW.js +1 -0
  88. package/ts/chunks/openai-TV7KLQ2C.js +1 -0
  89. package/ts/chunks/openai-YPM2E7QS.js +30 -0
  90. package/ts/chunks/opencode-AK6WWZRF.js +1 -0
  91. package/ts/chunks/pack-EOUSZGJT.js +5 -0
  92. package/ts/chunks/plan-export-ZBINRAAS.js +3 -0
  93. package/ts/chunks/purge-GPMC5A6Y.js +5 -0
  94. package/ts/chunks/reopen-LPVNZN5I.js +1 -0
  95. package/ts/chunks/reset-RNLPXGWQ.js +1 -0
  96. package/ts/chunks/review-ZGAY5XCN.js +1 -0
  97. package/ts/chunks/rule-SNBQ4VZD.js +6 -0
  98. package/ts/chunks/run-4TDP4C7Z.js +3 -0
  99. package/ts/chunks/sdk-MEVPL5WT.js +1 -0
  100. package/ts/chunks/session-J7TSLNEH.js +1 -0
  101. package/ts/chunks/spec-3NSPFDIC.js +1 -0
  102. package/ts/chunks/status-DIEA2OGR.js +1 -0
  103. package/ts/chunks/sync-HZNKILSP.js +1 -0
  104. package/ts/chunks/validate-MWHDOF2F.js +1 -0
  105. package/ts/chunks/vertexai-ARXI4AMJ.js +1 -0
  106. package/ts/chunks/watch-P6HABMAS.js +7 -0
  107. package/ts/chunks/web-BMIC3VJQ.js +1 -0
  108. package/ts/chunks/wontfix-6UKEYTVB.js +1 -0
  109. package/ts/noskills.js +2 -0
  110. package/chunks/anthropic-ZKOMTKX2.js +0 -1
  111. package/chunks/approve-3TKOHYHH.js +0 -1
  112. package/chunks/ask-UB26SBWQ.js +0 -2
  113. package/chunks/block-Q4WAIX7X.js +0 -1
  114. package/chunks/browser-BGFD24RX.js +0 -1
  115. package/chunks/bun-WZ7BVR7Y.js +0 -1
  116. package/chunks/cancel-DY76ADX4.js +0 -1
  117. package/chunks/chunk-34RPTI4K.js +0 -29
  118. package/chunks/chunk-3JTDWOAJ.js +0 -2
  119. package/chunks/chunk-5FX4EBFY.js +0 -5
  120. package/chunks/chunk-5RLCKUIF.js +0 -2
  121. package/chunks/chunk-7PBHRFOZ.js +0 -3
  122. package/chunks/chunk-7PPUGTKL.js +0 -4
  123. package/chunks/chunk-AB3N327V.js +0 -1
  124. package/chunks/chunk-AUZWXMWA.js +0 -27
  125. package/chunks/chunk-BYPCI5VU.js +0 -1
  126. package/chunks/chunk-CH6A3LES.js +0 -91
  127. package/chunks/chunk-CKIZYL4O.js +0 -3
  128. package/chunks/chunk-CTTMQSHF.js +0 -1
  129. package/chunks/chunk-DEHRWREM.js +0 -1
  130. package/chunks/chunk-DYCGJ4RY.js +0 -4
  131. package/chunks/chunk-ENP4P2YH.js +0 -0
  132. package/chunks/chunk-EVJYA7S3.js +0 -21
  133. package/chunks/chunk-FE4MKOI4.js +0 -1
  134. package/chunks/chunk-GNMOE7H3.js +0 -48
  135. package/chunks/chunk-HB62UGZI.js +0 -2
  136. package/chunks/chunk-IFE5SYGK.js +0 -1
  137. package/chunks/chunk-IM73MYMS.js +0 -1
  138. package/chunks/chunk-JYVB6UAV.js +0 -1
  139. package/chunks/chunk-KJLEPI7T.js +0 -1
  140. package/chunks/chunk-KRRPOVQG.js +0 -1
  141. package/chunks/chunk-LGQEWL5X.js +0 -1
  142. package/chunks/chunk-LJEWPIEI.js +0 -1
  143. package/chunks/chunk-LKZZ4JN5.js +0 -110
  144. package/chunks/chunk-NGCBWJML.js +0 -2
  145. package/chunks/chunk-NPWXEWRN.js +0 -4
  146. package/chunks/chunk-O4KKKYCH.js +0 -1
  147. package/chunks/chunk-ONJVI5AZ.js +0 -23
  148. package/chunks/chunk-OP4XAIGW.js +0 -1
  149. package/chunks/chunk-PSX63TYP.js +0 -2
  150. package/chunks/chunk-Q4TI7EYT.js +0 -5
  151. package/chunks/chunk-SLO22P65.js +0 -1
  152. package/chunks/chunk-T6NZVA6P.js +0 -7
  153. package/chunks/chunk-TCSIXKUD.js +0 -3
  154. package/chunks/chunk-VJRCTYGL.js +0 -1
  155. package/chunks/chunk-VXU6XZ66.js +0 -39
  156. package/chunks/chunk-WDKWHGJU.js +0 -146
  157. package/chunks/chunk-XDPATEP5.js +0 -1
  158. package/chunks/chunk-Y45DQJSS.js +0 -3
  159. package/chunks/chunk-Y5E7ZCCX.js +0 -1
  160. package/chunks/chunk-YUTDPPXX.js +0 -1
  161. package/chunks/chunk-Z7OYXH3J.js +0 -1
  162. package/chunks/claude-code-OQJIUKZP.js +0 -1
  163. package/chunks/cmd-46ZIHXLB.js +0 -1
  164. package/chunks/concern-UIGVWDFS.js +0 -1
  165. package/chunks/config-72Z4PIJN.js +0 -1
  166. package/chunks/decision-ledger-5IPPTRT7.js +0 -1
  167. package/chunks/delegate-OV6NY434.js +0 -1
  168. package/chunks/deno-YM5PW6ZM.js +0 -1
  169. package/chunks/diagrams-CBCUA47B.js +0 -1
  170. package/chunks/diagrams-OX4FBDGP.js +0 -1
  171. package/chunks/done-V54GSSTY.js +0 -1
  172. package/chunks/followup-NL7EPIGF.js +0 -1
  173. package/chunks/free-KD344KRL.js +0 -1
  174. package/chunks/gemini-23EOEXSF.js +0 -1
  175. package/chunks/init-WDRNFT57.js +0 -1
  176. package/chunks/invoke-hook-I3NTD36Q.js +0 -13
  177. package/chunks/kiro-TPAAIMY6.js +0 -1
  178. package/chunks/learn-WBWNJEB2.js +0 -7
  179. package/chunks/ledger-QYK252DV.js +0 -1
  180. package/chunks/list-WO6RS7JX.js +0 -1
  181. package/chunks/loader-command-3A5FK2RF.js +0 -1
  182. package/chunks/loader-reactor-YZM7HO4G.js +0 -1
  183. package/chunks/manager-ZSPRC5R4.js +0 -3
  184. package/chunks/mod-7VTKN6Q5.js +0 -1
  185. package/chunks/mod-B6LBGYON.js +0 -1
  186. package/chunks/mod-MMHDQRNF.js +0 -1
  187. package/chunks/mod-RBGAMGZA.js +0 -1
  188. package/chunks/mod-SFSUQWSB.js +0 -8
  189. package/chunks/mod-SV4VELMH.js +0 -1
  190. package/chunks/next-QXCLZ7P3.js +0 -15
  191. package/chunks/node-BXYZKSJY.js +0 -15
  192. package/chunks/node-DMUOWFGA.js +0 -69
  193. package/chunks/node-J4GTOSL2.js +0 -1
  194. package/chunks/ollama-MXRDGQDF.js +0 -1
  195. package/chunks/openai-LE47IWMQ.js +0 -30
  196. package/chunks/openai-MSJF4B6H.js +0 -1
  197. package/chunks/opencode-ZDHKR2P6.js +0 -1
  198. package/chunks/pack-NS64WU6M.js +0 -5
  199. package/chunks/plan-export-HECAF7D4.js +0 -3
  200. package/chunks/purge-PSQNN42H.js +0 -4
  201. package/chunks/reopen-L37M5XUI.js +0 -1
  202. package/chunks/reset-OOTZXW6Q.js +0 -1
  203. package/chunks/review-QLD6WSOB.js +0 -1
  204. package/chunks/rule-OOANQBHB.js +0 -6
  205. package/chunks/run-YHCIRY7Z.js +0 -3
  206. package/chunks/sdk-OQIHH3OY.js +0 -1
  207. package/chunks/session-OWWDH7KA.js +0 -1
  208. package/chunks/spec-O7F525UN.js +0 -1
  209. package/chunks/status-SZZXY7V3.js +0 -1
  210. package/chunks/sync-3RYRGTEA.js +0 -1
  211. package/chunks/unstable_chmod-44MCKF3B.js +0 -1
  212. package/chunks/validate-UZD6JBSG.js +0 -1
  213. package/chunks/vertexai-CVCRCO24.js +0 -1
  214. package/chunks/watch-5DNM646U.js +0 -8
  215. package/chunks/web-662LNB3K.js +0 -1
  216. package/chunks/wontfix-UDCTLHNB.js +0 -1
  217. package/chunks/workerd-I7MLRCLJ.js +0 -1
  218. /package/{chunks/chunk-5OTECUN7.js → ts/chunks/chunk-ATNTR7M5.js} +0 -0
  219. /package/{chunks → ts/chunks}/chunk-HISXAZ4Y.js +0 -0
  220. /package/{chunks → ts/chunks}/chunk-I4Z2RF7L.js +0 -0
  221. /package/{chunks → ts/chunks}/dist-3MH5UCQU.js +0 -0
  222. /package/{chunks → ts/chunks}/multipart-parser-DKDFOZKD.js +0 -0
  223. /package/{chunks → ts/chunks}/src-HXQVVTGQ.js +0 -0
@@ -0,0 +1,22 @@
1
+ import{d as ce,e as le}from"./chunk-SWRVSRYY.js";import{a as de,b as ue}from"./chunk-FLLYK5FU.js";import{c as _}from"./chunk-W7KQFMHV.js";import{b as J,d as H,g as ie}from"./chunk-TKBGNLNV.js";import{h as G}from"./chunk-XGRZPTAD.js";import{a as K,d as M,e as Y,g as se,h as z,i as oe,j as re}from"./chunk-XTQFSF6C.js";import{a as X,r as ae}from"./chunk-SWP6BJR6.js";import{C as B}from"./chunk-M4U4Y3XQ.js";var Q={detected:!1,reason:"",proposals:[]},Ie=[/\badditionally\b/i,/\bseparately\b/i,/\band also\b/i,/\banother issue\b/i,/\bsecond problem\b/i,/\bon the other hand\b/i,/\bplus\b/i],pe=/(?:^|[.!?]\s+)also[,\s]/im,De=/(?:^|\n|\.\s+)\s*(?:\(\d+\)|\d+\.\s|(?:first|second|third|fourth|fifth)[:;,])/im,Ae=/\b(fix|add|restore|update|remove|refactor|rewrite|implement|create|migrate|convert)\s+\S+(?:\s+\S+){0,4}\s+AND\s+(fix|add|restore|update|remove|refactor|rewrite|implement|create|migrate|convert)\s+/i,Oe=[/\buse\s+(?:the\s+)?(?:new\s+)?(\w+)\s+(?:type|interface|class|module|function)\b/i,/\bafter\s+(?:adding|creating|implementing)\b/i,/\bdepends\s+on\b/i,/\bprerequisite\b/i,/\brequires\s+(?:the\s+)?(?:above|previous|first)\b/i,/\bthen\s+use\b/i],me=(e,t)=>{if(t==="ship-fast")return Q;let n=new Map;for(let b of e)n.set(b.questionId,b.answer);let o=n.get("status_quo")??"",s=n.get("ambition")??"",r=n.get("scope_boundary")??"",i=n.get("verification")??"",l=Te(o,s,r,i);return l.length<2||l.reduce((b,m)=>b+m.estimatedTasks,0)<=3||Ve(l)?Q:{detected:!0,reason:`Discovery answers cover ${l.length} independent areas that could be separate specs.`,proposals:l}},Te=(e,t,n,o)=>{let s=Ne(e,t);if(s.length>=2)return s.map(Z);let r=$e(e,t);if(r.length>=2)return r.map(Z);let i=Ue(e,t);return i.length>=2?i.map(Z):[]},Ne=(e,t)=>{for(let[n,o]of[[e,"status_quo"],[t,"ambition"]]){if(!De.test(n))continue;let s=Fe(n);if(s.length>=2)return s.map(r=>({text:r.trim(),sourceQuestions:[o]}))}return[]},Fe=e=>{let n=e.split(/\(\d+\)\s*/).slice(1).map(d=>d.trim()).filter(d=>d.length>0);if(n.length>=2)return n;let o=e.split(/(?:^|\n|(?<=\.)\s+)\s*\d+\.\s+/),s=o.length>1?o.slice(1).map(d=>d.trim()).filter(d=>d.length>0):[];if(s.length>=2)return s;let r=/(?:^|\n|(?<=\.)\s+)\s*(?:first|second|third|fourth|fifth)[:;,]\s*/i,i=e.split(r),l=i.length>1?i.slice(1).map(d=>d.trim()).filter(d=>d.length>0):[];return l.length>=2?l:[]},$e=(e,t)=>{for(let[n,o]of[[e,"status_quo"],[t,"ambition"]]){if(pe.test(n)){let s=Le(n,pe);if(s.length>=2)return s.map(r=>({text:r.trim(),sourceQuestions:[o]}))}for(let s of Ie)if(s.test(n)){let r=n.split(s).map(i=>i.trim()).filter(i=>i.length>0);if(r.length>=2)return r.map(i=>({text:i,sourceQuestions:[o]}))}}return[]},Le=(e,t)=>{let n=e.match(t);if(n===null||n.index===void 0)return[];let o=e.slice(0,n.index).trim(),s=e.slice(n.index+n[0].length).trim();return o.length>0&&s.length>0?[o,s]:[]},Ue=(e,t)=>{for(let[n,o]of[[e,"status_quo"],[t,"ambition"]]){let s=Ae.exec(n);if(s!==null&&s.index!==void 0){let r=n.toUpperCase().indexOf(" AND ",s.index);if(r>=0){let i=n.slice(0,r).trim(),l=n.slice(r+5).trim();if(i.length>0&&l.length>0)return[{text:i,sourceQuestions:[o]},{text:l,sourceQuestions:[o]}]}}}return[]},Z=e=>{let t=Me(e.text),n=qe(e.text);return{name:t,description:e.text,estimatedTasks:n,relevantAnswers:[...e.sourceQuestions]}},Me=e=>{let t=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","shall","should","may","might","must","can","could","to","of","in","for","on","with","at","by","from","that","this","it","its","and","or","but","not","no","so","if","then","too","very","just"]),s=e.toLowerCase().replace(/[^a-z0-9\s-]/g,"").split(/\s+/).filter(r=>r.length>0&&!t.has(r)).slice(0,4).join("-").replace(/--+/g,"-").replace(/^-|-$/g,"").slice(0,50);return s.length>0?s:"area"},qe=e=>{let t=/\b(fix|add|restore|update|remove|refactor|rewrite|implement|create|migrate|convert|replace|extract|move|rename|split|merge|test|verify|validate|configure|setup|install|deploy)\b/gi,o=e.match(t)?.length??0;return Math.max(2,Math.min(o+1,5))},Ve=e=>{for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++){let o=e[t],s=e[n],r=`${o.description} ${s.description}`;for(let b of Oe)if(b.test(r))return!0;let i=he(o.description),l=he(s.description);if([...i].filter(b=>l.has(b)).some(b=>/^[A-Z]/.test(b)||b.includes(".")))return!0}return!1},he=e=>{let t=new Set,n=e.match(/\b[A-Z][a-zA-Z0-9]+\b/g);if(n!==null)for(let s of n)t.add(s);let o=e.match(/\b[\w-]+\.\w{1,4}\b/g);if(o!==null)for(let s of o)t.add(s);return t};var k=e=>_(e),a=(e,t)=>t==null?k(e):k(`spec ${t} ${e}`),fe=e=>e.length===0?"none":e.join(", "),Ge=[{key:"involvesWebUI",pattern:/\b(ui|frontend|component|react|css|html|button|modal|form|page|screen|layout|design|loading state|empty state|error state)\b/i},{key:"involvesCLI",pattern:/\b(cli|terminal|command.?line|stdout|stdin|ansi|tui|console)\b/i},{key:"involvesPublicAPI",pattern:/\b(api|endpoint|rest|graphql|webhook|public.?facing|sdk|client.?library)\b/i},{key:"involvesMigration",pattern:/\b(migrat\w*|schema.?change|breaking.?change|backward.?compat|upgrade|deprecat\w*)\b/i},{key:"involvesDataHandling",pattern:/\b(pii|gdpr|encrypt|personal.?data|user.?data|data.?retention|data.?safety|sensitive)\b/i}],xe=e=>{let t=[];e.specDescription!==null&&e.specDescription!==""&&t.push(e.specDescription);let n=e.discovery?.userContext;Array.isArray(n)&&t.push(...n);for(let r of e.discovery?.answers??[])t.push(r.answer);let o=t.join(" "),s={involvesWebUI:!1,involvesCLI:!1,involvesPublicAPI:!1,involvesMigration:!1,involvesDataHandling:!1,source:"inferred",inferredFrom:[]};for(let{key:r,pattern:i}of Ge){let l=o.match(i);l!==null&&(s[r]=!0,s.inferredFrom.push(`${r}:${l[0].toLowerCase()}`))}return s},Qe=[{key:"involvesWebUI",label:"Web UI"},{key:"involvesPublicAPI",label:"Public API"},{key:"involvesCLI",label:"CLI"},{key:"involvesMigration",label:"Migration"},{key:"involvesDataHandling",label:"Data Handling"}],je=e=>{let t=new Map;for(let o of e.inferredFrom??[]){let s=o.indexOf(":");if(s===-1)continue;let r=o.slice(0,s),i=o.slice(s+1),l=t.get(r);l===void 0?t.set(r,[i]):l.includes(i)||l.push(i)}let n=["Based on your answers, this spec involves:"];for(let{key:o,label:s}of Qe){let r=e[o]===!0,i=r?"\u2713":"\u2717";if(r){let l=t.get(o)??[];if(l.length>0){let d=l.map(b=>`"${b}"`).join(", ");n.push(` ${i} ${s} (mentions: ${d})`)}else n.push(` ${i} ${s}`)}else n.push(` ${i} ${s}`)}return n.join(`
2
+ `)},Xe="NEVER run git write commands (commit, add, push, checkout, stash, reset, merge, rebase, cherry-pick). Git is read-only for agents. The user controls git. You may read: git log, git diff, git status, git show, git blame.",ge="This phase is read-only: read files and run read-only commands (cat, ls, grep, git log, git diff); create or edit nothing and run nothing that changes state, apart from the noskills commands this output gives you.",ee=e=>e.planModeShortcut===void 0?ge:`${ge} If the session is not in plan mode, ask the user to switch (${e.planModeShortcut}).`,ye=["Interview the user about each part of this plan until you both share one understanding.","Walk down each branch of the design tree, resolving dependencies between decisions one-by-one.","For each question, provide your recommended answer \u2014 don't just ask, offer your informed opinion.",de(),"If a question can be answered by exploring the codebase, explore the codebase INSTEAD of asking. Only ask the user what the codebase cannot tell you.","Do NOT fill placeholders with assumptions; ask the user instead.","If a section is not applicable, ask the user to confirm it's N/A with a specific reason \u2014 don't decide yourself.","If two answers conflict, surface the conflict to the user \u2014 don't resolve it yourself.","If an answer is vague, push back and ask for specifics \u2014 don't accept vague."],Ke=e=>e.hasAskUserTool?"Ask the base questions through AskUserQuestion, as many as fit in each call (it takes up to 4), and each follow-up in a call of its own.":"Ask the base questions in one message, as a numbered list, and each follow-up in a message of its own.",ke={hasAskUserTool:!0,optionPresentation:"tool",hasSubAgentDelegation:!0,subAgentMethod:"task",planModeShortcut:"Shift+Tab"},ze=e=>{let t=["CEO REVIEW \u2014 PREMISE CHECK: Restate the core premise in one sentence. Does it still hold? What evidence supports it? What challenges it?","CEO REVIEW \u2014 READINESS DASHBOARD: Score 8 dimensions 1-10 (premise-clarity, reuse-leverage, test-coverage, failure-mode-coverage, boundary-clarity, unresolved-decisions, verification-path, scope-discipline). State overall score. Verdict: APPROVED or NEEDS WORK.","CEO REVIEW \u2014 REFLECTION: Honest observation of the user's decision patterns during this spec. Not flattery. If they made a questionable choice, say so respectfully."];return e==="hold-scope"?t:[...t,"CEO REVIEW \u2014 REUSE SCORE: Table of existing modules/functions reused vs new code. Calculate approximate reuse percentage. Flag if <40%.","CEO REVIEW \u2014 DREAM STATE DELTA: Current state, 12-month ideal, the share of that gap this spec delivers (%), and the remaining gap.","CEO REVIEW \u2014 FAILURE MODE REGISTRY: Table with #, Failure, Trigger, Mitigation. Every failure mode must have concrete mitigation. Include at minimum: data corruption, race conditions, backward compat, user confusion, performance.","CEO REVIEW \u2014 NOT IN SCOPE: Explicit list of what this spec does NOT touch, with reasons. This is a contract.","CEO REVIEW \u2014 UNRESOLVED DECISIONS: Table with #, Decision, Default, Notes. Every unresolved decision must have a safe default. Present to user.","CEO REVIEW \u2014 FILE-LEVEL PLAN: Table of every file created/modified with purpose. Plus: functions to reuse, files NOT modified.",e==="scope-expansion"?"CEO REVIEW \u2014 EXPANSION TABLE: Present all accepted expansions with LOC estimates.":"CEO REVIEW \u2014 SCOPE DISCIPLINE: List what was held out of scope and why."]},Je=e=>{let t=e.filter(o=>o.suggestsPosture!==void 0);return t.length===0?null:t.length===1?`Based on your active concerns, suggested posture: ${t[0].suggestsPosture} (${t[0].name} active).`:`Multiple concerns suggest different postures (${t.map(o=>`${o.name}: ${o.suggestsPosture}`).join(", ")}). Please select manually: a/b/c/d.`},Ze=(e,t,n,o,s,r)=>{let i=e.spec,l=i??"<name>",d=s.interactive!==!1,b=s.hasAskUserTool?"Use AskUserQuestion for all decision points.":"Present options as a numbered list at every decision point.",m=[];t||m.push(Xe),m.push("Report progress honestly. Not done = 'not done'. Partial = 'partial: [works]/[doesn't]'. Untested = 'untested'. 4 of 6 = '4 of 6 done, 2 remaining'.",d?`Never skip steps or infer decisions. ${b} Recommend first, then ask.`:`Never skip steps or infer decisions. Nobody answers questions during this run: when a decision needs the user, run \`${a('block "reason"',l)}\` and stop.`),d&&m.push("Display `roadmap` before other content. Display `gate` prominently."),m.push("NEVER suggest bypassing, skipping, or 'breaking out of' noskills. Discovery helps the user \u2014 it is not an obstacle. If scope changes: revise spec, reset and create new, or split.","Run the next noskills command as soon as the current step is done; each step has exactly one next step, so there is nothing to ask permission for."),d&&m.push("Listen first: after spec creation, ask 'Tell me about this. Share as much context as you have.' Wait for their response before mode selection. Rich context (>200 chars) \u2192 suggest pre-filled discovery answers from it, marked STATED or INFERRED for the user to confirm. Brief response \u2192 proceed normally.",`Discovery questions are adaptive. Once the user has answered the base questions, write 1-3 follow-up questions for each answer that reveals ambiguity, risk, dependencies, or missing detail, and register them with \`${a('followup <questionId> "question"',l)}\` before you submit the answers (max 3 per question). noskills then gives you the follow-ups one at a time.`),m.push("Confidence scoring: every technical finding needs a confidence score (1-10). 9-10: verified (read code, ran test). 7-8: strong evidence. 5-6: reasonable inference. 3-4: guess. 1-2: speculation. State basis ('read X', 'inferred from Y'). If confidence < 5, prefix with '\u26A0 Unverified:'.");let w=o?.outOfScope??[];switch(e.phase){case"IDLE":{let g=s.optionPresentation==="tool"?"Pass interactiveOptions DIRECTLY to AskUserQuestion options array (header max 12 chars). Use commandMap to resolve selections. For availableConcerns: AskUserQuestion with multiSelect:true, max 4 per question \u2014 split across questions if needed. Present ALL concerns.":"Present interactiveOptions as numbered list. Use commandMap to resolve selections. Present ALL availableConcerns as numbered list for multiselect.";return{rules:[`If the user described a feature/bug/task, create a spec immediately: \`${k('spec new "description"')}\`; the name is auto-generated. Do NOT present menus or ask 'What would you like to do?' unless the conversation has no prior context.`,...m,g,`Encourage full context: 'Tell me what you want to build: a one-liner, detailed requirements, meeting notes, anything.' Slug is auto-generated. Pass full text to \`${k('spec new "..."')}\`.`,"After spec new, run next and present the discovery mode options it returns; never skip discovery without asking.","Every task gets a spec. No exceptions. A one-liner fix, a config change, a 'simple' refactor \u2014 all get specs. The spec can be short but it must exist. 'Too simple for a spec' is the anti-pattern.",`SPEC CREATION: When the user says 'create a new spec', 'new spec', or similar, do NOT run \`${k("spec new")}\` without a description. Ask the user 'What do you want to build?'${s.hasAskUserTool?" via AskUserQuestion":""} first. Wait for their response. Then run: \`${k('spec new "their full response"')}\`.`,`CONCERN MANAGEMENT: When the user wants to add or view concerns, run \`${k("concern list")}\` immediately. Do NOT analyze or recommend concerns. ${s.optionPresentation==="tool"?"Present the list via AskUserQuestion (multiSelect:true, max 4 per question).":"Present the list as a numbered list; the user may pick several numbers."} Use a SINGLE \`${k("concern add id1 id2 id3")}\` command for all selections.`],tone:"Welcoming. Present choices, then wait."}}case"DISCOVERY":{let g=Ke(s),h=n.flatMap(c=>c.conductRules?.DISCOVERY??[]);return{modeOverride:"plan mode",rules:[...m,ee(s),`${g} Never answer questions yourself. With a fully formed plan, skip questions but MUST run premise challenge and alternatives.`,ue(a("next --answer",l)),"Pre-discovery: (1) pre-discovery codebase scan \u2014 read README, CLAUDE.md, design docs, last 20 commits, TODOs, existing specs, directory structure. Present a brief audit summary. (2) If `preDiscoveryResearch.required`, web-search every `extractedTerms` entry \u2014 report versions, API changes, deprecations. (3) Ask discovery mode: A) Explore scope B) Technical depth C) Validate my plan D) Ship fast. Adapt emphasis accordingly.","Before starting discovery questions, challenge the user's initial spec description against codebase findings. Flag: hidden complexity, conflicts with existing code, scope mismatch, overlapping modules. Ask clarifying follow-ups.","When asking questions, offer concrete options from codebase knowledge alongside the open-ended question (e.g., 'I see three scenarios: A)... B)... C)... D) Something else'). Push back on vague answers. Follow up on short answer with 'Can you be more specific?'",(()=>{let c=re(n);return`${c.length>0?`After answers, ${c.join(" Also: ")}`:"After answers, synthesize CURRENT STATE \u2192 THIS SPEC \u2192 6-MONTH IDEAL vision."} Then: (1) expansion opportunities as numbered proposals with effort (S/M/L/XL), risk, completeness delta \u2014 options: Add/Defer/Skip. (2) Architectural decisions that BLOCK implementation \u2014 present with options, RECOMMENDATION, completeness scores. Unresolved = risk flag. (3) Error/rescue map: codepath | failure mode | handling. Flag CRITICAL GAPS as decisions.`})(),"Present DISCOVERY SUMMARY for confirmation: intent, scope, dream state, expansions, architectural decisions, error map. Ask for confirmation before generating spec.",...ye,...h],tone:"Curious interviewer with a stake in the answers. Comes PREPARED \u2014 read the codebase first. Challenge assumptions, think about architecture and failure modes."}}case"DISCOVERY_REFINEMENT":{let g=n.flatMap(u=>u.conductRules?.DISCOVERY_REFINEMENT??[]),h=ne(e),c;if(h==="stage-a"){let u=Je(n),E=r?.defaultReviewPosture!==void 0;c=["COMPLETENESS ASSESSMENT: Before presenting answers for review, evaluate the spec's completeness across 6 dimensions. Score each 1-10: problem-clarity, scope-definition, technical-feasibility, verification-strategy, risk-identification, user-impact-analysis. Identify concrete gaps (specific, not vague). Present the table and gaps to the user.","Scoring guide: 9-10 = fully addressed; 7-8 = mostly addressed; 5-6 = partially; 3-4 = weakly; 1-2 = not addressed. A gap is anything the spec doesn't explicitly address that could cause problems during execution."],u!==null&&c.push(u),E?c.push(`Using project default posture: ${r.defaultReviewPosture} (from manifest.yml). To override, answer with a/b/c/d. Answer 'clear-posture' to remove this default.`):c.push("After presenting the completeness assessment, present the 4 review posture options: (a) Selective expansion \u2014 fill gaps only, no scope drift; (b) Hold scope \u2014 surface risks but no additions; (c) Scope expansion \u2014 actively explore adjacent features; (d) Scope reduction \u2014 cut to essentials. Ask user to choose."),c.push(s.hasAskUserTool?"Use AskUserQuestion to present the completeness table and posture options together in one question.":"Present completeness table and posture options in one message. User replies with 'a', 'b', 'c', or 'd'.")}else if(h==="stage-b"){let u=e.discovery.refinement?.reviewPosture;c=[u==="selective-expansion"?"REVIEW POSTURE: Selective expansion. Hold core scope rigid. Only suggest additions that address gaps from the completeness assessment. Each suggestion must explain: what gap it fills, what goes wrong if skipped. Target: raise completeness to 9+/10 with minimal additions.":u==="hold-scope"?"REVIEW POSTURE: Hold scope. Do NOT propose any additions or changes. Surface risks as observations, not change requests. Your job is to confirm the spec is ready, not to improve it.":u==="scope-expansion"?"REVIEW POSTURE: Scope expansion. Actively look for adjacent concerns and missing features. Each expansion must ride on infrastructure already being built. Present ALL suggestions as a multi-select table with columns: Addition | Why it rides cheap | LOC estimate.":"REVIEW POSTURE: Scope reduction. Identify everything that can be deferred. For each item: what's deferred, risk of deferring, minimal viable version. Present cut list for user approval."],e.discovery.refinement?.completenessScore!==void 0&&c.push("RE-ASSESSMENT: After posture-guided review is complete, re-score the 6 completeness dimensions. Show delta: what was addressed (\u2713), what remains (\u25B3). Submit updated score as JSON {completeness: {...}} before CEO review."),c.push("When posture-guided review is complete, produce the CEO REVIEW ANALYSIS (see CEO review protocol rules below). Submit it as JSON {ceoReview: {...}, reflection?: '...'} to record it."),c.push(...ze(u??"selective-expansion"))}else c=["CEO review is complete. Present the updated completeness score delta, the readiness dashboard verdict, and ask the user to advance (approve), revise, or park the spec.",s.hasAskUserTool?"Use AskUserQuestion to present: updated completeness (delta table), readiness verdict, and options: advance / revise / park.":"Present delta and verdict. User answers: approve (advance), revise (return to stage-a), or park (cancel)."];return{modeOverride:"plan mode",rules:[...m,ee(s),...c,...ye,...g],tone:h==="stage-a"?"Structured evaluator. Score honestly \u2014 do not inflate.":h==="stage-b"?"Posture-guided reviewer. Follow the posture rules exactly.":"Decisive closer. Present delta and get a final decision."}}case"SPEC_PROPOSAL":{let g=e.discovery.delegations??[],h=[];if(g.length>0){let c=g.filter(y=>y.status==="pending"),u=g.filter(y=>y.status==="answered"),E=g.map(y=>`- ${y.questionId}: delegated to ${y.delegatedTo} \u2014 ${y.status==="answered"?"ANSWERED \u2713":"PENDING"}`);h.push(`DELEGATION STATUS:
3
+ ${E.join(`
4
+ `)}${c.length>0?`
5
+ Approve BLOCKED \u2014 ${c.length} pending delegation(s).`:`
6
+ All ${u.length} delegation(s) answered. Approve is allowed.`}`)}return{modeOverride:"plan mode",rules:[...m,...h,ee(s),"Read the spec and present a summary to the user.","Flag any tasks that are too vague to execute.","Flag any missing acceptance criteria.","No placeholders in specs. If a task has 'TBD', 'TODO', 'to be determined', 'details to follow', or 'implement appropriate X' \u2014 fill in the detail or remove the task and add it as an open question.","Ask the user if they want to refine before approving.",s.hasAskUserTool?"When presenting classification options, use AskUserQuestion with multiSelect:true. Do NOT infer classification yourself.":"When presenting classification options, present them as a numbered list with multiselect (user picks multiple numbers). Do NOT infer classification yourself.","When generating or refining tasks, include a 'Files:' hint listing likely files to create/modify. Format: 'Files: `path/to/file.ts`, `path/to/other.ts`'. Hints, not constraints \u2014 helps sub-agents load right context.","If you identify issues in the spec (vague tasks, irrelevant sections, missing acceptance criteria), submit a refinement via: `"+a(`next --answer='{"refinement":"task-1: Add upload endpoint, task-2: Add validation middleware, task-3: Write integration tests"}'`,i)+"`. The spec will be updated and you can review again."],tone:"Thoughtful reviewer preparing to hand off to an implementer."}}case"SPEC_APPROVED":return{rules:[...m,"The spec is approved but execution has not started.","Do not start coding until the user triggers execution.","If the user wants changes, they must reset and re-spec.",s.hasAskUserTool?"Before starting execution, show the spec summary to the user and ask for final confirmation via AskUserQuestion.":"Before starting execution, show the spec summary to the user and ask for final confirmation. Present 'Start execution' and 'Not yet' as numbered options."],tone:"Patient. Wait for the go signal."};case"EXECUTING":{let g=a(`next --answer='{"completed":[...],"remaining":[...],"blocked":[...]}'`,i),h,c,u="Verifier scope: (1) AC verification with evidence. (2) Plan alignment \u2014 does implementation match task description? Flag deviations. (3) Code quality \u2014 follows existing patterns? Flag style breaks, missing error handling. Categorize findings: CRITICAL (blocks completion), IMPORTANT (should fix), SUGGESTION (nice to have).";s.subAgentMethod==="task"?(h=`Spawn noskills-executor via Agent tool. Pass: task title, description, ACs, rules, scope constraints, concern reminders, file paths. Report via \`${g}\`.`,c=`After executor completes, spawn noskills-verifier with changed files + ACs + test commands. Never trust executor self-report alone. ${u}`):s.subAgentMethod==="spawn"?(h=`Use spawn_agent for noskills-executor. Pass: task, ACs, rules, scope, file paths. Use wait_agent to collect. Report via \`${g}\`.`,c=`After executor completes, spawn noskills-verifier with changed files + ACs + test commands. ${u}`):s.subAgentMethod==="fleet"?(h=`Use /fleet for parallel executors. Pass each: task, ACs, rules, scope, file paths. Report via \`${g}\`.`,c=`After fleet completes, run verification pass. ${u}`):s.subAgentMethod==="delegation"?(h=`Use Kiro agent delegation for noskills-executor. Pass: task, ACs, rules, scope, file paths. Report via \`${g}\`.`,c=`After executor completes, delegate to noskills-verifier with changed files + ACs + test commands. ${u}`):(h=`Execute tasks sequentially yourself. Verify (type-check + tests) after each. Report via \`${g}\`.`,c="");let E=s.subAgentMethod!=="none",y=E?`You are the orchestrator. NEVER edit files directly \u2014 delegate ALL edits to noskills-executor. ${h} On sub-agent failure, fall back to direct execution and note it in status.`:h,x=[...m,"MODE: You MUST NOT be in plan mode during execution. If you are in plan mode, exit it now. Sub-agents need full write access.",y,...c!==""?[c]:[],"Do not explore beyond current task. Do not refactor outside scope. Do not add features, tests, or docs not in the spec.",...E?["Show a dispatch table: | Step | Agent | Files | Tasks | Est. |. Separate executor for implementation vs tests. Batch tightly-coupled files; parallelize independent modules."]:[],"Run type-check and lint after edits; never mark an AC passed while type-check fails.",...d?[`On recurring patterns or corrections, ask: 'Permanent rule or just this task?' If permanent: \`${k('rule add "<description>"')}\`. Never write to \`.eser/rules/\` directly.`]:[],"Work through the spec's tasks to the end; the user decides when to stop.","Base every status claim on evidence: run the command, read the output, report what it showed.","TDD: (1) Write test. (2) Run it \u2014 MUST fail. If it passes before implementation, the test is wrong. (3) Implement. (4) Run test \u2014 must pass. Skipping step 2 means the test is unverified.","Parallel vs serial sub-agents: PARALLEL when tasks touch different files with no shared state. SERIAL when tasks modify same files or depend on each other. When unsure, default to serial.",...E?["After each task, spawn noskills-verifier and include its PASS/FAIL results in the status report before reporting the task done."]:["VERIFICATION REQUIRED: After EVERY task completion, run type-check + tests before reporting done. Evidence of passing tests must be included in the status report."]];return e.execution.lastVerification?.passed===!1&&x.push("Tests are failing. Fix ONLY the failing tests. Do not refactor passing code."),{rules:x,tone:"Direct. Orchestrate immediately \u2014 spawn sub-agents.",outOfScope:w.length>0?w:void 0}}case"BLOCKED":return{rules:[...m,"MODE: Enter plan mode. Analyze the blocker. Present options to the user. Do not edit files.","Present the decision to the user exactly as described.","Do not suggest a preferred option unless the user asks for your opinion.",`After the user decides, submit the decision right away with \`${a('next --answer="<decision>"',l)}\`.`],tone:"Brief. The user is making a decision, not having a discussion."};case"COMPLETED":return{rules:[...m,"Report the completion summary. Do not start new work.","If the user wants to continue, they start a new spec."],tone:"Concise. Celebrate briefly, then stop."};default:return{rules:[...m,`Run \`${a("next",i)}\` to get your instructions.`,"Do not take action without noskills guidance."],tone:"Neutral. Waiting for direction."}}},et=300*1e3,tt=e=>{let n=e.hasSubAgentDelegation?"enforced":"behavioral";return n==="enforced"?{level:n,capabilities:["PreToolUse file edit gate","Git write guard","Stop iteration tracking","PostToolUse file logging","Sub-agent delegation"]}:{level:n,capabilities:["Behavioral rules only"],gaps:["File edits not blocked in non-execution phases","Git write commands not blocked","No iteration tracking","No file change logging","No sub-agent delegation available"]}},nt=(e,t,n=ke)=>{let o=e.spec,s;switch(e.phase){case"IDLE":s=`No active spec. Start one with: \`${k('spec new --name=<slug> "description"')}\``;break;case"DISCOVERY":s=`Discovery in progress for "${e.spec}". ${e.discovery.answers.length} questions answered so far.`;break;case"DISCOVERY_REFINEMENT":s=`Discovery answers ready for review. ${e.discovery.answers.length} answers collected. Waiting for user confirmation.`;break;case"SPEC_PROPOSAL":s=`Spec draft ready for review at ${e.specState.path}. Waiting for approval.`;break;case"SPEC_APPROVED":s=`Spec "${e.spec}" is approved. Waiting to start execution.`;break;case"EXECUTING":s=e.execution.lastProgress!==null?`Executing "${e.spec}", iteration ${e.execution.iteration}. Last progress: ${e.execution.lastProgress}. Continue with the current task.`:`Executing "${e.spec}", iteration ${e.execution.iteration}. Start the first task.`;break;case"BLOCKED":s=`Execution blocked: ${e.execution.lastProgress}. Ask the user to resolve.`;break;case"COMPLETED":s=`Spec "${e.spec}" completed in ${e.execution.iteration} iterations.`;break;default:s=`Run \`${a("next",o)}\` to get started.`}let r=tt(n);return{protocol:`Run \`${a('next --answer="..."',o)}\` to submit results and advance`,spec:e.spec,branch:e.branch,iteration:e.execution.iteration,lastProgress:e.execution.lastProgress,activeConcerns:t.map(i=>i.id),resumeHint:s,enforcement:r}},st=e=>{let t=e.spec;if(e.lastCalledAt===null)return{what:"noskills orchestrates your work: IDLE \u2192 DISCOVERY \u2192 DISCOVERY_REFINEMENT \u2192 SPEC_PROPOSAL \u2192 SPEC_APPROVED \u2192 EXECUTING \u2192 DONE \u2192 IDLE",how:`Run \`${a("next",t)}\` for instructions. Submit results with \`${a('next --answer="..."',t)}\`. Never make architectural decisions without asking.`,currentPhase:e.phase};let n=new Date(e.lastCalledAt).getTime();if(Date.now()-n>et)return{what:"noskills orchestrates your work: IDLE \u2192 DISCOVERY \u2192 DISCOVERY_REFINEMENT \u2192 SPEC_PROPOSAL \u2192 SPEC_APPROVED \u2192 EXECUTING \u2192 DONE \u2192 IDLE",how:`Run \`${a("next",t)}\` for instructions. Submit results with \`${a('next --answer="..."',t)}\`. Never make architectural decisions without asking.`,currentPhase:e.phase}},ve=[{key:"IDLE",label:"IDLE"},{key:"DISCOVERY",label:"DISCOVERY"},{key:"DISCOVERY_REFINEMENT",label:"REFINEMENT"},{key:"SPEC_PROPOSAL",label:"PROPOSAL"},{key:"SPEC_APPROVED",label:"APPROVED"},{key:"EXECUTING",label:"EXECUTING"},{key:"COMPLETED",label:"COMPLETED"},{key:"IDLE_END",label:"IDLE"}],ot=e=>e==="BLOCKED"?ve.map(t=>t.key==="EXECUTING"?"[ EXECUTING (BLOCKED) ]":t.label).join(" \u2192 "):ve.map(t=>t.key==="IDLE"&&e==="IDLE"?"[ IDLE ]":t.key===e?`[ ${t.label} ]`:t.label).join(" \u2192 "),rt=(e,t)=>{switch(e.phase){case"DISCOVERY_REFINEMENT":{let n=G(e.specState),o=`${e.discovery.answers.length}/6 answers collected.`;if(!n.canAdvance){let s=n.unresolvedSections.length+n.pendingDecisions.length;return{message:`${o} Spec incomplete: ${s} item(s) need resolution before advancing.`,action:`Resolve every placeholder + pending decision before approving. Do NOT advance until 100%. Unresolved: ${fe(n.unresolvedSections.map(r=>r.sectionTitle))}. Pending: ${fe(n.pendingDecisions.map(r=>r.section))}.`+(n.unresolvedSections.length>0?` Ask the user about each unresolved section. ${te(e.spec??"<name>")}`:""),phase:"DISCOVERY_REFINEMENT"}}return{message:`${o} All sections resolved.`,action:"Type APPROVE to generate spec, or REVISE to correct answers.",phase:"DISCOVERY_REFINEMENT"}}case"SPEC_APPROVED":return{message:`Spec approved. ${t?.tasks?.length??0} tasks ready.`,action:"Type START to begin execution.",phase:"SPEC_APPROVED"};default:return}},Ut=async(e,t,n,o,s,r,i,l,d,b,m)=>{let w=l??ke,g=nt(e,t,w),h=o?.maxIterationsBeforeRestart??15,c=o?.allowGit??!1,u=Ze(e,c,t,s,w,o);if(e.phase==="EXECUTING"){let C=b??0,F=Y(t,e.classification).tier2.length,f=C+F;f>0&&(u={...u,tier2Summary:`${f} file-specific rules delivered via PreToolUse hook when editing matching files.`})}let E=st(e),y;switch(e.phase){case"IDLE":y=we(t,K,n.length,i);break;case"DISCOVERY":y=await gt(e,t,n,w,d,m);break;case"DISCOVERY_REFINEMENT":y=yt(e,t,w);break;case"SPEC_PROPOSAL":y=vt(e);break;case"SPEC_APPROVED":y=wt(e);break;case"EXECUTING":y=St(e,t,n,h,w,s,r);break;case"BLOCKED":y=xt(e);break;case"COMPLETED":y=await kt(e,m);break;default:y=we(t,K,n.length,i)}let x=ot(e.phase),L=rt(e,s),R={...y,meta:g,behavioral:u,roadmap:x};L!==void 0&&(R={...R,gate:L}),E!==void 0&&(R={...R,protocolGuide:E});let N=Ce[e.phase];N!==void 0&&(R={...R,modeDirective:N});let S=it(e,t,i,y);if(S.length>0){let C=S.map(({label:P,description:V})=>({label:P,description:V})),F={};for(let P of S)F[P.label]=P.command;let f=w.optionPresentation==="tool"?"AskUserQuestion":"prose-numbered-list",$=w.optionPresentation==="tool"?"Present these options with AskUserQuestion so the user's pick maps to `commandMap`.":"Present options as a numbered list. Ask user to pick a number.";R={...R,interactiveOptions:C,commandMap:F,toolHint:f,toolHintInstruction:$}}return R},it=(e,t,n,o)=>{let s=e.spec;switch(e.phase){case"DISCOVERY":{let r=o;if(r?.activePlanDetected!==void 0){let i=r.activePlanDetected;return[{label:`Convert plan (${i.age})`,description:`Import ${i.path} as STATED pre-fill for discovery`,command:a('next --answer="import-plan"',s)},{label:"Share my own context",description:"Start fresh \u2014 tell me what you want to build",command:a('next --answer="<your context here>"',s)}]}return[]}case"IDLE":{let r=[],l=(n?.existingSpecs??[]).filter(d=>d.phase!=="COMPLETED");t.length===0&&r.push({label:"Add concerns (Recommended)",description:"Shape how discovery and specs work by adding project concerns",command:k("concern add <id> [<id2> ...]")}),r.push({label:"Start a new spec",description:"Tell me what you want to build: a one-liner, detailed requirements, meeting notes, anything",command:k('spec new "description"')});for(let d of l.slice(0,2))r.push({label:`Continue: ${d.name} (${d.phase})`,description:d.detail??`Iteration ${d.iteration}`,command:a("next",d.name)});return t.length>0&&r.push({label:"Edit concerns",description:`Currently: ${t.map(d=>d.id).join(", ")}`,command:k("concern list")}),r.slice(0,4)}case"DISCOVERY_REFINEMENT":return e.discovery.approved?[{label:"Keep as one spec",description:"All work in a single spec",command:a('next --answer="keep"',s)},{label:"Split into separate specs",description:"Create one spec per independent area",command:a('next --answer="split"',s)}]:[{label:"Approve all answers",description:"Answers look correct \u2014 generate the spec",command:a('next --answer="approve"',s)},{label:"Revise answers",description:"Correct one or more discovery answers",command:a(`next --answer='{"revise":{...}}'`,s)}];case"SPEC_PROPOSAL":return[{label:"Approve spec",description:"Review looks good \u2014 approve and move to execution",command:a("approve",s)},{label:"Refine spec",description:"Submit refinements to improve tasks or sections",command:a(`next --answer='{"refinement":"..."}'`,s)},{label:"Save for later",description:"Keep the draft as-is. Others can review, add ACs, notes, or tasks. Come back anytime to approve.",command:a('next --answer="save"',s)},{label:"Start over",description:"Reset the spec and start fresh",command:a("reset",s)}];case"SPEC_APPROVED":return[{label:"Start execution",description:"Begin implementing the tasks",command:a('next --answer="start"',s)},{label:"Save for later",description:"Spec is approved but don't start execution yet. Others can still add ACs or notes.",command:a('next --answer="save"',s)}];case"EXECUTING":return[];case"BLOCKED":return[{label:"Resolve block",description:"Provide a resolution to unblock execution",command:a('next --answer="resolution"',s)},{label:"Reset spec",description:"Abandon this spec and start over",command:a("reset",s)}];case"COMPLETED":return[{label:"New spec",description:"Start a new feature spec",command:k('spec new --name=<slug> "description"')},{label:"Reopen spec",description:"Reopen this spec for revision",command:a("reopen",s)},{label:"Check status",description:"Review completed spec summary",command:k("status")}];default:return[]}},at="noskills is a state-machine orchestrator that acts as a scrum master for both you and your agent \u2014 keeping work focused, decisions in your hands, and tokens efficient.",we=(e,t,n,o)=>({phase:"IDLE",instruction:(o?.existingSpecs??[]).length===0?`No specs yet. Ask the user "What do you want to build?" and accept any input, then run \`${k('spec new "their answer"')}\` immediately. Do NOT list options or ask clarifying questions first.`:`No active spec. If the user described what they want, run \`${k('spec new "description"')}\` immediately; the name is auto-generated. Present ALL available concerns (split across multiple calls if needed).`,welcome:at,existingSpecs:o?.existingSpecs??[],availableConcerns:t.map(s=>({id:s.id,description:s.description})),activeConcerns:e.map(s=>s.id),activeRulesCount:o?.rulesCount??n,behavioralNote:"These options are fallbacks. If the user already described what they want, act on it directly without presenting these options.",hint:e.length===0?"No concerns active. Consider adding concerns first \u2014 they shape discovery questions and specs.":void 0}),ct=/\b(Node\.?js|Deno|Bun|Go|Rust|Python|Ruby|Java|Kotlin|Swift|PHP|React|Vue|Angular|Svelte|Next\.?js|Nuxt|Remix|Astro|SolidJS|Qwik|TypeScript|Webpack|Vite|esbuild|Rollup|Terraform|Docker|Kubernetes|PostgreSQL|MySQL|Redis|MongoDB|SQLite|Prisma|Drizzle|gRPC|GraphQL|tRPC)\s+v?(\d+(?:\.\d+)?(?:\.\d+)?\+?)\b/gi,lt=e=>{if(e===null||e.length===0)return[];let t=[],n,o=new RegExp(ct.source,"gi");for(;(n=o.exec(e))!==null;)t.push(`${n[1]} ${n[2]}`);return t},Ee=e=>{let t=lt(e);if(t.length!==0)return{required:!0,instruction:"Before asking discovery questions, research the current state of all platforms, runtimes, libraries, and APIs mentioned in the spec description. Use web search and Context7 MCP if available. Report findings as a pre-discovery brief to the user. Do NOT assume your training data is current \u2014 versions change, APIs get added, features get deprecated.",extractedTerms:t}},Re=50*1024,be=async e=>{if(e!==null)try{let t=await B.fs.readTextFile(e);return t.length>Re?void 0:{provided:!0,content:t,instruction:"A plan document was provided. Read it carefully, extract relevant information for each discovery question, and present pre-filled answers for user review. Do NOT skip any question \u2014 present your extraction and let the user confirm, correct, or expand. When extracting answers from the plan, mark each extraction as [STATED] (directly written in the plan) or [INFERRED] (your interpretation). Present extractions individually for confirmation."}}catch{return}},Ce={IDLE:"No active spec. Plan mode optional.",DISCOVERY:"Ensure you are in plan mode. Read-only. Analyze, research, ask.",DISCOVERY_REFINEMENT:"Ensure you are in plan mode. Read-only. Review answers, resolve placeholders.",SPEC_PROPOSAL:"Ensure you are in plan mode. Use ultraplan if available. Generate implementation map with file dependencies and execution order.",SPEC_APPROVED:"Exit plan mode. Prepare for execution.",EXECUTING:"Ensure you have exited plan mode. Sub-agents need full write access.",BLOCKED:"Enter plan mode. Analyze the blocker. Present options to user.",COMPLETED:"Plan mode optional. Review, record learnings."},Mt=e=>Ce[e],dt=async(e,t=Date.now())=>{let n=[`${e}/plan.md`,`${e}/PLAN.md`,`${e}/.claude/plan.md`];for(let o of n)try{let s=await B.fs.stat(o),r=s.mtime??s.birthtime;if(r===null)continue;let i=t-r.getTime();if(i>1440*60*1e3)continue;let l=await B.fs.readTextFile(o);if(l.length>Re)continue;let d=l.replace(/^---[\s\S]*?---\n?/,""),m=d.split(`
7
+ `).filter(u=>u.trim().length>0).slice(0,3).join(`
8
+ `).slice(0,200),w=d.replace(/\s/g,"").length,g=/^## /m.test(d),h=w>=100&&g?"ok":"sparse",c=i<6e4?"just now":Math.floor(i/36e5)>0?`${Math.floor(i/36e5)}h ago`:`${Math.floor(i%36e5/6e4)}m ago`;return{path:o,age:i,ageLabel:c,preview:m,quality:h}}catch{continue}return null},ut=e=>{let t=[],n=e.toLowerCase(),o=["websocket","graphql","grpc","redis","postgres","mongodb","kafka","rabbitmq","docker","kubernetes","lambda","s3"];for(let s of o)n.includes(s)&&t.push(`Answer mentions ${s} \u2014 consider: error handling, versioning, fallback strategy`);return(n.includes("should work")||n.includes("standard approach")||n.includes("probably")||n.includes("i think")||n.includes("not sure"))&&t.push("Answer is vague \u2014 ask for specifics"),(n.includes("and also")||n.includes("we might")||n.includes("could also")||n.includes("maybe we should"))&&t.push("Scope expansion signal \u2014 clarify if in scope or deferred"),(n.includes("tricky")||n.includes("complicated")||n.includes("risky")||n.includes("not sure about"))&&t.push("Risk signal \u2014 dig deeper into what makes it risky"),(n.includes("depends on")||n.includes("after")||n.includes("blocked by")||n.includes("waiting for"))&&t.push("Dependency detected \u2014 clarify what happens if dependency isn't ready"),(n.includes("real-time")||n.includes("scalab")||n.includes("performance")||n.includes("latency")||n.includes("concurrent"))&&t.push("Performance/scale mention \u2014 ask about limits, degradation, monitoring"),t},pt=e=>{switch(e){case"full":return["Ask each discovery question as written. Push for specific, concrete answers.","If the answer is vague, ask follow-up questions before accepting."];case"validate":return["The user has a plan. Your job is to challenge it, not explore it.","For each question, identify assumptions and ask: 'What would prove this wrong?'","If the description already answers a question, present your understanding and ask to confirm.","When pre-filling answers from a rich description, plan, or prior discussion, DISTINGUISH between what the user EXPLICITLY STATED and what you INFERRED. Format each pre-filled item as: '[STATED] GPU skinning in all 3 renderers \u2014 you said this during technical discussion' or '[INFERRED] tangent space is 10-star scope \u2014 I assumed this based on complexity'. The user confirms stated items and corrects inferred items.","Present each pre-filled answer as an item of its own that the user confirms or corrects, not as one completed block. The user's job is to correct your inferences, not rubber-stamp your summary. If you pre-fill 5 items and 2 are wrong, the user must be able to catch them individually."];case"technical-depth":return["Focus on architecture, data flow, performance, and integration points.","Before each question, scan the codebase for related implementations.","Ask: 'How does this interact with [existing system]?' for each integration point."];case"ship-fast":return["Focus on minimum viable scope.","For each question, also ask: 'What can we defer to a follow-up?'","Push for the smallest version that delivers value."];case"explore":return["Think bigger. What's the 10x version?","For each question, ask about adjacent opportunities.","Suggest possibilities the user might not have considered."]}},ht=(e,t)=>{let n=new Map;for(let o of e){let s="user"in o?o.user:"Unknown User";t!==void 0&&s===t.name||n.set(s,(n.get(s)??0)+1)}return[...n.entries()].map(([o,s])=>({name:o,contributions:`${s} answer${s>1?"s":""}`}))},Se=e=>JSON.stringify(Object.fromEntries(e.map(t=>[t.id,"..."]))),mt=(e,t,n,o)=>{let s;return e===1?s=t.hasAskUserTool?"Ask the user this discovery question through AskUserQuestion and wait for the answer.":"Ask the user this discovery question and wait for the answer.":t.hasAskUserTool?e>4?s=`Ask the user these ${e} discovery questions together through AskUserQuestion, up to 4 questions per call, and wait for the answers.`:s=`Ask the user these ${e} discovery questions together in one AskUserQuestion call and wait for the answers.`:s=`Ask the user these ${e} discovery questions together in one message, as a numbered list, and wait for the answers.`,`${s} For an answer that needs a follow-up, register it with \`${n}\` first. Then submit the confirmed answers as one JSON object: \`${o}\`. noskills then gives you each follow-up on its own.`},ft=(e,t,n,o,s)=>{let r=t[0],i=n.find(h=>h.id===r.parentQuestionId),l=a(`followup ${r.id} --answer="<answer>"`,e.spec),d=a(`followup ${r.id} --skip`,e.spec),b=o.hasAskUserTool?"Ask the user this follow-up on its own, as the only question of an AskUserQuestion call, and wait for the answer.":"Ask the user this follow-up on its own and wait for the answer.",m=i!==void 0?` It follows up the answer to "${i.text}".`:"",w=t.length-1,g=w===0?"Discovery moves on to the review once this one is answered or skipped.":`${w} more follow-up${w===1?" comes":"s come"} after this one, each on its own.`;return{phase:"DISCOVERY",instruction:`${b}${m} Submit the answer with \`${l}\`, or run \`${d}\` if the user declines it. ${g}`,questions:[{id:r.id,text:r.question,concerns:[...i?.concerns??[]],extras:[]}],answeredCount:e.discovery.answers.length,context:s,transition:{onComplete:l},pendingFollowUps:t}},gt=async(e,t,n,o,s,r)=>{let i=e.spec,l=J(t),d=e.discovery.answers.length,b=H(e.discovery.answers),m=e.discovery.audience==="agent",w=ht(e.discovery.answers,s),g=(e.specNotes??[]).filter(p=>!p.text.startsWith("[TASK] ")).map(p=>({text:p.text,user:p.user})),h={...s!==void 0?{currentUser:s}:{},...w.length>0?{previousContributors:w}:{},...g.length>0?{notes:g}:{}},c=ie(e),u=e.discovery.planPath!==null,E=e.discovery.mode;if(c==="listen"){let p=null;r!==void 0&&(p=await dt(r));let v=p?.quality==="sparse"?`
9
+ \u26A0 The plan appears sparse \u2014 limited content detected.`:"",T={phase:"DISCOVERY",instruction:"The user just created this spec. Before starting discovery, ask them to share whatever context they have (requirements, notes, tasks, or just a brief description). Say: 'Tell me about this. Share as much context as you have.' Listen first, then proceed."+(p!==null?`
10
+
11
+ A plan.md was detected (${p.ageLabel}, ${p.path}).${v}
12
+ You can import it or share your own context directly.`:""),questions:[],answeredCount:0,context:{rules:n,concernReminders:M(t,e.classification)},transition:{onComplete:a('next --answer="<user context or just start>"',i)},...h,...p!==null?{activePlanDetected:{path:p.path,age:p.ageLabel,preview:p.preview,quality:p.quality}}:{}};return s!==void 0?{...T,currentUser:s}:T}let y=u?{planImported:!0}:{};if(c==="mode"){let v={phase:"DISCOVERY",instruction:"Before starting discovery, select the discovery mode that best fits this spec.",questions:[],answeredCount:0,context:{rules:n,concernReminders:M(t,e.classification)},transition:{onComplete:a('next --answer="<mode>"',i)},modeSelection:{required:!0,instruction:"Select the discovery mode.",options:[{id:"full",label:"Full discovery",description:"Standard 6 questions with all concern extras. Default for new features."},{id:"validate",label:"Validate my plan",description:"I already know what I want \u2014 challenge my assumptions, find gaps."},{id:"technical-depth",label:"Technical depth",description:"Focus on architecture, data flow, performance, integration points."},{id:"ship-fast",label:"Ship fast",description:"Minimum viable scope. What can we defer? What's the MVP?"},{id:"explore",label:"Explore scope",description:"Think bigger. 10x version? Adjacent opportunities? What are we missing?"}]}};if(r!==void 0)try{let A=await ce(r,e.specDescription??"");A.length>0&&(v={...v,previousLearnings:le(A)})}catch{}return s!==void 0?{...v,currentUser:s}:v}if(c==="premises"){let p=E==="ship-fast"?["Narrowest Wedge: What's the absolute minimum version of this that creates real, measurable value \u2014 without any surrounding features?"]:E==="explore"?["Demand Reality: What do users actually do today when they can't use this feature? Describe concrete workarounds \u2014 not hypothetical ones.","Status Quo: Why hasn't this been solved before? What existing solution is insufficient, and specifically where does it break down?","Desperate Specificity: Describe the exact moment a real user feels this pain \u2014 who, where, what did they do next?","Narrowest Wedge: What's the smallest version of this that creates real value?","Observation & Surprise: What's the most surprising thing you know about this problem or this user?","Think bigger: If this works perfectly, what's the 10x version? What should you build next?"]:["Demand Reality: What do users actually do today when they can't use this feature? Describe concrete workarounds \u2014 not hypothetical ones.","Status Quo: Why hasn't this been solved before? What existing solution is insufficient, and specifically where does it break down?","Desperate Specificity: Describe the exact moment a real user feels this pain. Name them if possible. What did they do next?","Narrowest Wedge: What's the smallest version of this that creates real, measurable value \u2014 without the surrounding features?","Observation & Surprise: What's the most surprising thing you've learned from watching real users encounter this problem?","Future-Fit: If this works perfectly in 6 months, what should you build next? Does that constrain any decisions you're making now?"],v={phase:"DISCOVERY",instruction:"Before asking discovery questions, challenge the premises of this spec.",questions:[],answeredCount:0,context:{rules:n,concernReminders:M(t,e.classification)},transition:{onComplete:a(`next --answer='{"premises":[...]}'`,i)},...y,premiseChallenge:{required:!0,instruction:"Read the spec description"+(e.discovery.planPath!==null?" and the plan document":"")+'. Identify 2-4 premises the spec assumes. Present each premise and ask the user to agree or disagree. Submit as JSON: {"premises":[{"text":"...","agreed":true/false,"revision":"..."}]}',prompts:p}};return s!==void 0?{...v,currentUser:s}:v}let x=E!==void 0?pt(E):[],L=[...n,...x],R=e.specDescription??"",N=R.length>500,S=e.discovery.premises??[],C=S.filter(p=>p.agreed).map(p=>p.text),F=S.filter(p=>!p.agreed&&p.revision!==void 0).map(p=>({original:p.text,revision:p.revision})),f=j(e);if(b&&f.length>0)return{...ft(e,f,l,o,{rules:L,concernReminders:M(t,e.classification)}),...h,...y};if(b){let v=(e.revisitHistory??[]).at(-1)??null,A={phase:"DISCOVERY",instruction:v!==null?`This spec was revisited from ${v.from}. All previous answers are preserved. Review and approve, or revise answers before regenerating the spec.`:`All discovery questions answered. Run: \`${a("approve",i)}\``,questions:[],answeredCount:d,context:{rules:n,concernReminders:[]},transition:{onComplete:a("approve",i)},...h,...y};if(v!=null){let T=v;return{...A,revisited:!0,revisitReason:T.reason,previousProgress:{completedTasks:[...T.completedTasks],totalTasks:T.completedTasks.length}}}return A}let $=new Set(e.discovery.answers.map(p=>p.questionId)),P=l.filter(p=>!$.has(p.id)).map(p=>({id:p.id,text:p.text,concerns:[...p.concerns],extras:p.extras.map(v=>v.text)}));if(m){let p=a(`next --agent --answer='${Se(P)}'`,i),v={phase:"DISCOVERY",instruction:mt(P.length,o,a('followup <questionId> "question"',i),p),questions:P,answeredCount:d,totalQuestions:l.length,context:{rules:L,concernReminders:M(t,e.classification)},transition:{onComplete:p},...h,...y,...C.length>0?{agreedPremises:C}:{},...F.length>0?{revisedPremises:F}:{},...f.length>0?{pendingFollowUps:f}:{}},A=e.discovery.answers.flatMap(T=>ut(T.answer).map(W=>`${T.questionId}: ${W}`));if(A.length>0&&(v={...v,followUpHints:A}),d===0){let T=Ee(e.specDescription??null);T!==void 0&&(v={...v,preDiscoveryResearch:T});let W=await be(e.discovery.planPath??null);W!==void 0&&(v={...v,planContext:W}),N&&W===void 0&&(v={...v,richDescription:{provided:!0,length:R.length,content:R,instruction:"The user provided a detailed description. For each question, extract relevant info and present as a pre-filled suggestion. When extracting answers from the description, mark each extraction as [STATED] (directly written by the user) or [INFERRED] (your interpretation). Present extractions individually for confirmation."}})}return v}let I=(e.revisitHistory??[]).at(-1)??null,O=I!==null,D={phase:"DISCOVERY",instruction:I!==null?`This spec was revisited from ${I.from}. Previous discovery answers are preserved \u2014 review and revise as needed, or approve to regenerate tasks.`:`Conduct a thorough discovery conversation. FIRST: perform a pre-discovery codebase scan (README, CLAUDE.md, recent git log, TODOs, directory structure) and present a brief audit summary. THEN: challenge the user's spec description against your findings. THEN: ask the unanswered discovery questions together, offering concrete options based on codebase knowledge, and register a follow-up for each unclear answer with \`${a('followup <questionId> "question"',i)}\` before you submit; noskills then gives you each follow-up on its own. AFTER questions: present a dream state table (current \u2192 this spec \u2192 future), scored expansion proposals, architectural decisions, and an error/rescue map. FINALLY: present a complete discovery synthesis for user confirmation before submitting answers as a JSON object.`,questions:P,answeredCount:d,context:{rules:L,concernReminders:M(t,e.classification)},transition:{onComplete:a(`next --answer='${Se(P)}'`,i)},...h,...y,...C.length>0?{agreedPremises:C}:{},...F.length>0?{revisedPremises:F}:{}};if(O&&I!==void 0)return{...D,revisited:!0,revisitReason:I.reason,previousProgress:{completedTasks:[...I.completedTasks],totalTasks:I.completedTasks.length}};if(d===0){let p=D,v=Ee(e.specDescription??null);v!==void 0&&(p={...p,preDiscoveryResearch:v});let A=await be(e.discovery.planPath??null);if(A!==void 0&&(p={...p,planContext:A}),N&&A===void 0&&(p={...p,richDescription:{provided:!0,length:R.length,content:R,instruction:"The user provided a detailed description. For each question, extract relevant info and present as a pre-filled suggestion."}}),p!==D)return p}return D},yt=(e,t,n)=>{let o=e.spec,s=J(t),r=e.discovery.answers.map(h=>{let c=s.find(u=>u.id===h.questionId);return{questionId:h.questionId,question:c?.text??h.questionId,answer:h.answer}}),i=me(e.discovery.answers);if(e.discovery.approved&&i.detected)return{phase:"DISCOVERY_REFINEMENT",instruction:"Discovery answers are approved. noskills detected multiple independent work areas in this spec. Present the split proposal to the user and let them decide whether to keep as one spec or split into separate specs.",answers:r,transition:{onApprove:a('next --answer="keep"',o),onRevise:a(`next --answer='{"revise":{"status_quo":"corrected answer"}}'`,o)},splitProposal:i};let l=e.discovery.alternativesPresented===!0;if(e.discovery.approved&&!l)return{phase:"DISCOVERY_REFINEMENT",subPhase:"alternatives",instruction:"Based on discovery answers, propose 2-3 distinct implementation approaches. Present each with name, summary, effort (S/M/L/XL), risk (Low/Med/High), pros, and cons. Ask the user to choose one, or skip.",answers:r,transition:{onApprove:a(`next --answer='{"approach":"A","name":"...","summary":"...","effort":"M","risk":"Low"}'`,o),onRevise:a('next --answer="skip"',o)},alternatives:{required:!0,instruction:n.optionPresentation==="tool"?"Generate 2-3 approaches from discovery answers and codebase. Present via AskUserQuestion.":"Generate 2-3 approaches from discovery answers and codebase. Present them as a numbered list and ask the user to pick one.",format:{fields:["id","name","summary","effort","risk","pros","cons"]}}};let d=e.discovery.batchSubmitted===!0?" These answers arrived in one batch, so noskills cannot tell whether the user confirmed each one. Present each answer on its own and get the user's confirmation for each before approving.":"",b=z(t),m=oe(t),w;if(b.length>0){let h=b.map(u=>({id:u.id,label:u.label,prompt:u.prompt,evidenceRequired:u.evidenceRequired,isRegistry:m.includes(u.id),concernId:u.concernId})),c=h.some(u=>u.isRegistry);w={dimensions:h,instruction:`Before approving, review the plan against each dimension below. For dimensions marked evidenceRequired, cite specific files or code. Present findings to the user for each dimension${n.hasAskUserTool?" via AskUserQuestion":""}, one dimension at a time, and wait for the reply before the next.`,...c?{registryInstruction:"Registry dimensions (isRegistry=true) require a structured table with every row filled. These tables will be included in the generated spec."}:{}}}let g=e.classification!==null&&e.classification.source==="inferred"?je(e.classification):void 0;return{phase:"DISCOVERY_REFINEMENT",instruction:i.detected?`Present ALL discovery answers to the user for review. ALSO present the split proposal \u2014 noskills detected multiple independent areas.${d}`:`Present ALL discovery answers to the user for review. The user must confirm or correct each answer before the spec can be generated.${n.hasAskUserTool?" Use AskUserQuestion to ask for confirmation.":""}${d}`,answers:r,transition:{onApprove:a('next --answer="approve"',o),onRevise:a(`next --answer='{"revise":{"status_quo":"corrected answer"}}'`,o)},splitProposal:i.detected?i:void 0,reviewChecklist:w,classificationPreview:g,subPhase:ne(e),completenessScore:e.discovery.refinement?.completenessScore,reviewPosture:e.discovery.refinement?.reviewPosture}},vt=e=>{let t=e.spec;return e.classification===null?{phase:"SPEC_PROPOSAL",instruction:"Before generating the spec, classify what this spec involves. Ask the user to select all that apply.",specPath:e.specState.path??"",transition:{onApprove:`${a(`next --answer='{"involvesWebUI":false,"involvesCLI":false,"involvesPublicAPI":false,"involvesMigration":false,"involvesDataHandling":false}'`,t)}`},classificationRequired:!0,classificationPrompt:{options:[{id:"involvesWebUI",label:"Web/Mobile UI \u2014 layouts, responsive design, visual components"},{id:"involvesCLI",label:"CLI/Terminal UI \u2014 spinners, progress bars, interactive prompts"},{id:"involvesPublicAPI",label:"Public API changes"},{id:"involvesMigration",label:"Data migration or schema changes"},{id:"involvesDataHandling",label:"Data handling or privacy"}],instruction:"Select all that apply. Submit as JSON: `"+a(`next --answer='{"involvesWebUI":true,"involvesCLI":false,"involvesPublicAPI":false,...}'`,t)+"`. If none apply, answer with: `"+a('next --answer="none"',t)+"`"}}:{phase:"SPEC_PROPOSAL",instruction:"Spec draft is ready. Self-review before presenting to user.",specPath:e.specState.path??"",transition:{onApprove:a("approve",t)},selfReview:{required:!0,checks:["Placeholder scan: no TBD, TODO, vague requirements","Consistency: tasks match discovery, ACs match tasks","Scope: single spec, not multiple independent subsystems","Ambiguity: every AC has one interpretation"],instruction:"Review draft against these checks. Fix issues inline before presenting to user. Do not ask user to fix \u2014 fix it yourself."}}},wt=e=>{let t=e.spec;return{phase:"SPEC_APPROVED",instruction:"Spec is approved and ready. When the user is ready to start, begin execution.",specPath:e.specState.path??"",transition:{onStart:`${a('next --answer="start"',t)}`}}},Et=(e,t)=>{if(t===null)return!1;let n=e.toLowerCase();return n.includes("mobile")||n.includes("layout")||n.includes("interaction design")?t.involvesWebUI:n.includes("ui state")||n.includes("skeleton ui")?t.involvesWebUI||t.involvesCLI:n.includes("readme")||n.includes("documentation updated")||n.includes("reflected in")&&n.includes("docs")?!0:n.includes("api doc")||n.includes("public api")?t.involvesPublicAPI:n.includes("migration")||n.includes("backward compat")||n.includes("deprecat")?t.involvesMigration:n.includes("audit trail")||n.includes("access control")||n.includes("data handling")||n.includes("data retention")?t.involvesDataHandling:!0},bt=(e,t,n,o,s,r,i,l,d,b)=>{if(d==="review-gate"){let E=e.filter(x=>(x.reviewDimensions??[]).length>0)[b??0];return E===void 0?[]:z([E],s).map(x=>({id:`gate-${E.id}-${x.id}`,text:`(${E.id} \u2014 ${x.label}) ${x.prompt}${x.evidenceRequired?" [EVIDENCE REQUIRED \u2014 cite file paths, line numbers, or test names]":""}`}))}let m=[],w=new Set(l??[]),g=0,h=()=>`ac-${++g}`;if(o!==null)for(let c of o.items)w.has(c.id)||m.push({id:c.id,text:`[DEBT from iteration ${c.since}] ${c.text}`});if(t&&m.push({id:h(),text:`[FAILED] Tests \u2014 fix this first: ${n.slice(0,200)}`}),r!=null)for(let c of r.verification){let u=h();w.has(u)||m.push({id:u,text:c})}for(let c of e)if(c.acceptanceCriteria!==void 0&&c.acceptanceCriteria.length>0)for(let u of c.acceptanceCriteria){if(!Et(u,s))continue;let E=h();w.has(E)||m.push({id:E,text:`(${c.id}) ${u}`})}if(i!==void 0)for(let c of i){let u=h();w.has(u)||m.push({id:u,text:`(folder: ${c.folder}) ${c.rule}`})}if(r!=null){let c=r.tasks?.find(u=>u.files!==void 0&&u.files.length>0);c?.files!==void 0&&c.files.length>0&&m.push({id:"scope-check",text:`Scope check: only files listed in task (${c.files.join(", ")}) should be modified. Report any out-of-scope changes with justification.`})}return m.push({id:"mandatory-tests",text:"Tests written and passing for all new and changed behavior"}),m.push({id:"mandatory-docs",text:"Documentation updated for all public-facing changes"}),m},St=(e,t,n,o,s,r,i)=>{let l=e.spec,d=se(t),b=e.execution.iteration>=o,m=e.execution.lastVerification?.passed===!1,w=e.execution.lastVerification?.output??"",g=r?.tasks??[],h=e.execution.completedTasks??[],c=new Set(h),u=g.find(f=>!c.has(f.id))??null,E=u!==null?{id:u.id,title:u.title,totalTasks:g.length,completedTasks:h.length,...u.files!==void 0&&u.files.length>0?{files:u.files}:{}}:void 0;if(e.execution.awaitingStatusReport){let f=e.execution.criteriaScope,$=e.execution.gateConcernCursor,P=bt(t,m,w,e.execution.debt,e.classification,r,i,e.execution.naItems,f,$),V;if(f==="review-gate"){let O=t.filter(v=>(v.reviewDimensions??[]).length>0),U=$??0,D=O[U],p=O.length;V=D!==void 0?`REVIEW GATE (${U+1}/${p}): Evaluate the ${D.name} concern dimensions against the actual implementation. Point to specific files, line numbers, and test names. File edits are BLOCKED \u2014 this is a review-only pass. Submit: ${a(`next --answer='{"completed":[...],"remaining":[...]}'`,l)}`:"Review gate complete \u2014 submit to advance."}else{let O=[];try{let U=JSON.parse(e.execution.lastProgress??"");Array.isArray(U.completed)&&(O=U.completed.filter(D=>typeof D=="string"&&D.startsWith("task-")))}catch{}V=O.length>=2?`${O.length} tasks reported complete. Report status against ALL relevant acceptance criteria.`:"Before this task is accepted, report your completion status against these acceptance criteria."}let I={phase:"EXECUTING",instruction:V,context:{rules:n,concernReminders:Y(t).tier1},transition:{onComplete:`${a(`next --answer='{"completed":[...],"remaining":[...],"blocked":[...]}'`,l)}`,onBlocked:f!=="review-gate"?`${a('block "reason"',l)}`:void 0,iteration:e.execution.iteration},statusReportRequired:!0,statusReport:{criteria:P,reportFormat:f==="review-gate"?{completed:"list dimension IDs you verified with evidence (file:line, test name)",remaining:"list dimension IDs not yet verified",blocked:"list dimension IDs that need a decision before you can verify"}:{completed:"list item IDs you finished (e.g., ['debt-1', 'ac-3']) with evidence",remaining:"list item IDs not yet done",blocked:"list item IDs that need a decision from the user",na:"(optional) list item IDs that are not applicable to this task \u2014 they will be removed from future criteria",newIssues:"(optional) list NEW issues discovered during implementation \u2014 free text, will be assigned debt IDs automatically"}},...f==="review-gate"?{subphase:"review-gate"}:{}};if(f!=="review-gate"){let O=[];try{let U=JSON.parse(e.execution.lastProgress??"");Array.isArray(U.completed)&&(O=U.completed.filter(D=>typeof D=="string"&&D.startsWith("task-")))}catch{}O.length>=2&&(I={...I,batchTasks:O})}return m&&f!=="review-gate"&&(I={...I,verificationFailed:!0,verificationOutput:w.slice(0,2e3)}),I}let y=(e.execution.lastProgress??"").includes("Task not accepted"),x=e.execution.debt?.items??[],L=e.execution.debt?.unaddressedIterations??0,R=E!==void 0?`Execute task ${E.id}: ${E.title} (${E.completedTasks}/${E.totalTasks} completed)`:"All tasks completed. Run `"+a("done",l)+"` to finish.",N;if(m)N="Verification FAILED. Fix the failing tests before continuing.";else if(y&&x.length>0){let f=L>=3?` These items have been outstanding for ${L} iterations.`:"";N=`Task not accepted \u2014 ${x.length} remaining item(s) must be addressed before this task can be completed.${f} Address them, then submit a new status report.`}else N=R;let S={phase:"EXECUTING",instruction:N,task:E,context:{rules:n,concernReminders:Y(t).tier1},transition:{onComplete:`${a('next --answer="..."',l)}`,onBlocked:`${a('block "reason"',l)}`,iteration:e.execution.iteration}};if(y&&x.length>0&&(S={...S,taskRejected:!0,rejectionReason:`${x.length} remaining item(s) must be addressed.`,rejectionRemaining:x.map(f=>f.text)}),e.execution.debt!==null&&e.execution.debt.items.length>0){let f=e.execution.debt.unaddressedIterations??0,$=f>=3?`These items have been open for ${f} iterations. Address them before any new work.`:"These were not completed in a previous iteration. Address them BEFORE starting new work.";S={...S,previousIterationDebt:{fromIteration:e.execution.debt.fromIteration,items:e.execution.debt.items,note:$}}}if(m){let f=w.slice(0,2e3);S={...S,verificationFailed:!0,verificationOutput:f}}if(d.length>0){let f=d.map(P=>`${P.between.join(" vs ")}: ${P.issue}`).join("; "),$=s.interactive===!1?`The user must choose which side to prioritize, and nobody answers during this run: run \`${a('block "concern tension: <which concerns>"',l)}\` and stop.`:s.hasAskUserTool?"You MUST present these to the user and get explicit resolution for each before proceeding. Use AskUserQuestion to ask which side to prioritize.":"You MUST present these to the user and get explicit resolution for each before proceeding. Ask which side to prioritize as a numbered list.";S={...S,concernTensions:d,instruction:`TENSION GATE: ${d.length} concern tension(s) detected: ${f}. ${$}`}}b&&(S={...S,restartRecommended:!0});let C=[...e.decisions].reverse().find(f=>!f.promoted);return C!==void 0&&(e.execution.lastProgress??"").startsWith("Resolved:")&&(S={...S,promotePrompt:{decisionId:C.id,question:C.question,choice:C.choice,prompt:`You just resolved a decision: "${C.choice}". Ask the user: "Should this be a permanent rule for future specs too?" If yes, run: \`${k(`rule add "${C.choice}"`)}\``}}),e.execution.iteration===0&&!m&&!y&&(S={...S,preExecutionReview:{instruction:"Re-read spec before starting. Flag: missing info that will block mid-execution, wrong task order, unclear ACs. Better to catch now than mid-execution."}}),t.some(f=>f.id==="beautiful-product")&&(S={...S,designChecklist:{required:!0,instruction:"Before completing any UI task, rate your implementation 0-10 on these dimensions and include the ratings in your AC report:",dimensions:[{id:"hierarchy",label:"Information hierarchy \u2014 what does the user see first, second, third?"},{id:"states",label:"Interaction states \u2014 loading, empty, error, success all specified?"},{id:"edge-cases",label:"Edge cases \u2014 long text, zero results, slow connection handled?"},{id:"intentionality",label:"Overall intentionality \u2014 does this feel designed or generated?"}]}}),S},xt=e=>{let t=e.spec;return{phase:"BLOCKED",instruction:"A decision is needed. Ask the user.",reason:e.execution.lastProgress??"Unknown",transition:{onResolved:`${a('next --answer="..."',t)}`}}},kt=async(e,t)=>{let o={phase:"COMPLETED",summary:{spec:e.spec,iterations:e.execution.iteration,decisionsCount:e.decisions.length,completionReason:e.completionReason,completionNote:e.completionNote},learningPrompt:{instruction:`LEARNING PENDING: record learnings before moving on. For each insight, decide: one-time learning or permanent rule? One-time ("assumed X, was Y") \u2192 \`learn "text"\`. Permanent ("always/never do X") \u2192 \`learn "text" --rule\`. Run: \`${a('learn "text"',e.spec??"<name>")}\` or \`learn "text" --rule\`.`,examples:[a('learn "Assumed S3 SDK v2, was v3"',e.spec??"upload"),a('learn "Always use Result types" --rule',e.spec??"upload"),k("learn promote 1")]},learningsPending:!0};if(t!==void 0)try{let{checkStaleness:s}=await import("./diagrams-H62JGTIS.js"),r=await s(t,e.execution.modifiedFiles);if(r.length>0)return{...o,staleDiagrams:r.map(i=>({file:i.file,line:i.line,reason:i.reason})),staleDiagramsBlocking:!0}}catch{}return o};var Pe={UNINITIALIZED:["IDLE"],IDLE:["DISCOVERY","COMPLETED"],DISCOVERY:["DISCOVERY_REFINEMENT","COMPLETED"],DISCOVERY_REFINEMENT:["DISCOVERY_REFINEMENT","SPEC_PROPOSAL","COMPLETED"],SPEC_PROPOSAL:["SPEC_PROPOSAL","SPEC_APPROVED","COMPLETED"],SPEC_APPROVED:["EXECUTING","COMPLETED"],EXECUTING:["COMPLETED","BLOCKED"],BLOCKED:["EXECUTING","COMPLETED"],COMPLETED:["IDLE","DISCOVERY"]},Ct=(e,t)=>Pe[e].includes(t),q=(e,t)=>{if(!Ct(e,t))throw new Error(`Invalid phase transition: ${e} \u2192 ${t}. Allowed: ${Pe[e].join(", ")}`)},_t=(e,t)=>(q(e.phase,t),{...e,phase:t}),Wt=(e,t,n,o)=>(q(e.phase,"DISCOVERY"),{...e,phase:"DISCOVERY",spec:t,specDescription:o??null,branch:n,discovery:{answers:[],completed:!1,currentQuestion:0,audience:"human",approved:!1,planPath:null},specState:{path:null,status:"none",metadata:X,placeholders:[]},execution:{iteration:0,lastProgress:null,modifiedFiles:[],lastVerification:null,awaitingStatusReport:!1,debt:null,completedTasks:[],debtCounter:0,naItems:[]},decisions:[]}),Bt=(e,t)=>{if(e.phase!=="DISCOVERY")throw new Error(`Cannot set discovery mode in phase: ${e.phase}`);return{...e,discovery:{...e.discovery,mode:t,entryComplete:!0}}};var Yt=(e,t)=>{if(e.phase!=="DISCOVERY")throw new Error(`Cannot complete premises in phase: ${e.phase}`);return{...e,discovery:{...e.discovery,premises:t,premisesCompleted:!0}}},Ht=(e,t)=>{if(e.phase!=="DISCOVERY_REFINEMENT")throw new Error(`Cannot select approach in phase: ${e.phase}`);return{...e,discovery:{...e.discovery,selectedApproach:t,alternativesPresented:!0}}},Gt=e=>{if(e.phase!=="DISCOVERY_REFINEMENT")throw new Error(`Cannot skip alternatives in phase: ${e.phase}`);return{...e,discovery:{...e.discovery,alternativesPresented:!0}}},Qt=(e,t,n,o)=>{if(e.phase!=="DISCOVERY"&&e.phase!=="DISCOVERY_REFINEMENT")throw new Error(`Cannot add discovery answer in phase: ${e.phase}`);if(n.trim().length<20)throw new Error("Answer too short. Discovery answers must be meaningful (minimum 20 characters).");let s=e.discovery.answers.filter(i=>i.questionId!==t),r={questionId:t,answer:n,user:o?.name??"Unknown User",email:o?.email??"",timestamp:new Date().toISOString(),type:"original"};return{...e,discovery:{...e.discovery,answers:[...s,r]}}};var Pt=e=>{if(e.phase!=="DISCOVERY")throw new Error(`Cannot complete discovery in phase: ${e.phase}`);let t=j(e);if(t.length>0)throw new Error(`Cannot complete discovery: ${t.length} pending follow-up(s). Answer or skip them first.`);return{...e,phase:"DISCOVERY_REFINEMENT",discovery:{...e.discovery,completed:!0},specState:{...e.specState,path:ae.specFile(e.spec),status:"draft"}}},jt=e=>e.phase!=="DISCOVERY"||!H(e.discovery.answers)||j(e).length>0?e:Pt(e),It=e=>e.classification!==null?e:{...e,classification:xe(e)},te=e=>`Record each answer with \`${_(`spec ${e} section <id> fill "text"`)}\`, or mark a section that does not apply with \`${_(`spec ${e} section <id> na "reason"`)}\`; \`${_(`spec ${e} section list`)}\` shows the ids.`,Xt=e=>{let t=G(e.specState);if(!t.canAdvance){let n=t.unresolvedSections.map(s=>` - ${s.sectionTitle} (${s.sectionId})`).join(`
13
+ `),o=t.pendingDecisions.map(s=>` - ${s.section}: ${s.question} (waiting for ${s.waitingFor.join(", ")})`).join(`
14
+ `);throw new Error(`Spec incomplete \u2014 cannot advance to SPEC_PROPOSAL.
15
+ `+(t.unresolvedSections.length>0?`
16
+ Unresolved sections:
17
+ ${n}`:"")+(t.pendingDecisions.length>0?`
18
+ Pending decisions:
19
+ ${o}`:"")+`
20
+
21
+ Ask the user to resolve every item. Do not guess, infer, or fill in yourself.`+(t.unresolvedSections.length>0?`
22
+ ${te(e.spec??"<name>")}`:""))}return q(e.phase,"SPEC_PROPOSAL"),It({...e,phase:"SPEC_PROPOSAL"})},Kt=e=>{if(e.phase!=="DISCOVERY_REFINEMENT")throw new Error(`Cannot approve discovery answers in phase: ${e.phase}`);return{...e,discovery:{...e.discovery,approved:!0}}},zt=e=>{if(e.phase!=="DISCOVERY")throw new Error(`Cannot advance discovery question in phase: ${e.phase}`);return{...e,discovery:{...e.discovery,currentQuestion:e.discovery.currentQuestion+1}}},Jt=e=>(q(e.phase,"SPEC_APPROVED"),{...e,phase:"SPEC_APPROVED",specState:{...e.specState,status:"approved"}}),Zt=e=>(q(e.phase,"EXECUTING"),{...e,phase:"EXECUTING",discovery:{...e.discovery,completed:!0,approved:!1},execution:{iteration:0,lastProgress:null,modifiedFiles:[],lastVerification:null,awaitingStatusReport:!1,debt:null,completedTasks:[],debtCounter:0,naItems:[]}});var en=(e,t)=>(q(e.phase,"BLOCKED"),{...e,phase:"BLOCKED",execution:{...e.execution,lastProgress:`BLOCKED: ${t}`}}),tn=(e,t)=>({...e,decisions:[...e.decisions,t]}),nn=(e,t,n)=>(q(e.phase,"COMPLETED"),{...e,phase:"COMPLETED",completionReason:t,completedAt:new Date().toISOString(),completionNote:n??null}),sn=e=>{if(e.phase!=="COMPLETED")throw new Error(`Cannot reopen in phase: ${e.phase}`);return{...e,phase:"DISCOVERY",reopenedFrom:e.completionReason,completionReason:null,completedAt:null,completionNote:null,discovery:{...e.discovery,completed:!1,currentQuestion:0,refinement:void 0},execution:{iteration:0,lastProgress:null,modifiedFiles:[],lastVerification:null,awaitingStatusReport:!1,debt:null,completedTasks:[],debtCounter:0,naItems:[]},classification:null}},on=(e,t)=>{if(e.phase!=="EXECUTING"&&e.phase!=="BLOCKED")throw new Error(`Cannot revisit in phase: ${e.phase}. Only EXECUTING or BLOCKED can revisit.`);let n={from:e.phase,reason:t,completedTasks:[...e.execution.completedTasks],timestamp:new Date().toISOString()};return{...e,phase:"DISCOVERY",discovery:{...e.discovery,completed:!1,currentQuestion:0,approved:!1,refinement:void 0},execution:{iteration:0,lastProgress:null,modifiedFiles:[],lastVerification:null,awaitingStatusReport:!1,debt:null,completedTasks:[],debtCounter:0,naItems:[]},classification:null,revisitHistory:[...e.revisitHistory??[],n]}},ne=e=>{let t=e.discovery.refinement;return t?.reviewPosture===void 0?"stage-a":t.ceoReview===void 0?"stage-b":"stage-c"},rn=(e,t)=>{if(e.phase!=="DISCOVERY_REFINEMENT")throw new Error(`setCompletenessScore: invalid phase ${e.phase}`);let n=e.discovery.refinement;return{...e,discovery:{...e.discovery,refinement:{...n,initialCompletenessScore:n?.initialCompletenessScore??t,completenessScore:t}}}},an=(e,t)=>{if(e.phase!=="DISCOVERY_REFINEMENT")throw new Error(`setReviewPosture: invalid phase ${e.phase}`);return{...e,discovery:{...e.discovery,refinement:{...e.discovery.refinement,reviewPosture:t}}}},cn=(e,t,n)=>{if(e.phase!=="DISCOVERY_REFINEMENT")throw new Error(`setCeoReviewReadiness: invalid phase ${e.phase}`);return{...e,discovery:{...e.discovery,refinement:{...e.discovery.refinement,ceoReview:{readinessScore:t,reflection:n}}}}},ln=e=>{if(e.phase!=="DISCOVERY_REFINEMENT")throw new Error(`clearRefinement: invalid phase ${e.phase}`);return{...e,discovery:{...e.discovery,refinement:void 0}}},dn=(e,t,n,o,s)=>{let r={from:t,to:n,user:o?.name??"Unknown User",email:o?.email??"",timestamp:new Date().toISOString(),reason:s},i=e.transitionHistory??[];return{...e,transitionHistory:[...i,r]}},un=(e,t,n)=>{let o=e.customACs??[],r={id:`custom-ac-${o.length+1}`,text:t,user:n?.name??"Unknown User",email:n?.email??"",timestamp:new Date().toISOString(),addedInPhase:e.phase};return{...e,customACs:[...o,r]}},pn=(e,t,n)=>{let o=e.specNotes??[],r={id:`note-${o.length+1}`,text:t,user:n?.name??"Unknown User",email:n?.email??"",timestamp:new Date().toISOString(),phase:e.phase};return{...e,specNotes:[...o,r]}},hn=(e,t)=>({...e,discovery:{...e.discovery,userContext:[...e.discovery.userContext??[],t],userContextProcessed:!1}}),mn=(e,t,n)=>({...e,discovery:{...e.discovery,userContext:[t],planPath:n}});var Dt=3,fn=(e,t,n,o)=>{let s=e.discovery.followUps??[],r=s.filter(d=>d.parentQuestionId===t).length;if(r>=Dt)return e;let l={id:`${t}${String.fromCharCode(97+r)}`,parentQuestionId:t,question:n,answer:null,status:"pending",createdBy:o,createdAt:new Date().toISOString()};return{...e,discovery:{...e.discovery,followUps:[...s,l]}}},gn=(e,t,n)=>{let s=(e.discovery.followUps??[]).map(r=>r.id===t&&r.status==="pending"?{...r,answer:n,status:"answered",answeredAt:new Date().toISOString()}:r);return{...e,discovery:{...e.discovery,followUps:s}}},yn=(e,t)=>{let o=(e.discovery.followUps??[]).map(s=>s.id===t&&s.status==="pending"?{...s,status:"skipped"}:s);return{...e,discovery:{...e.discovery,followUps:o}}},j=e=>(e.discovery.followUps??[]).filter(t=>t.status==="pending"),vn=(e,t)=>(e.discovery.followUps??[]).filter(n=>n.parentQuestionId===t),wn=(e,t,n,o)=>{let s=e.discovery.delegations??[],r={questionId:t,delegatedTo:n,delegatedBy:o,status:"pending",delegatedAt:new Date().toISOString()};return{...e,discovery:{...e.discovery,delegations:[...s,r]}}},En=(e,t,n,o)=>{let r=(e.discovery.delegations??[]).map(i=>i.questionId===t&&i.status==="pending"?{...i,status:"answered",answer:n,answeredBy:o,answeredAt:new Date().toISOString()}:i);return{...e,discovery:{...e.discovery,delegations:r}}},bn=e=>(e.discovery.delegations??[]).filter(t=>t.status==="pending"),At=new Set(["IDLE","EXECUTING","BLOCKED","COMPLETED"]),Ot=e=>At.has(e)?null:`Cannot reset from ${e}. Use \`cancel\` or \`wontfix\` instead.`,Sn=e=>{let t=Ot(e.phase);if(t!==null)throw new Error(t);return{...e,phase:"IDLE",spec:null,branch:null,discovery:{answers:[],completed:!1,currentQuestion:0,audience:"human",approved:!1,planPath:null},specState:{path:null,status:"none",metadata:X,placeholders:[]},execution:{iteration:0,lastProgress:null,modifiedFiles:[],lastVerification:null,awaitingStatusReport:!1,debt:null,completedTasks:[],debtCounter:0,naItems:[]},decisions:[],classification:null,completionReason:null,completedAt:null,completionNote:null,reopenedFrom:null}};export{_t as a,Wt as b,Bt as c,Yt as d,Ht as e,Gt as f,Qt as g,Pt as h,jt as i,It as j,Xt as k,Kt as l,zt as m,Jt as n,Zt as o,en as p,tn as q,nn as r,sn as s,on as t,ne as u,rn as v,an as w,cn as x,ln as y,dn as z,un as A,pn as B,hn as C,mn as D,fn as E,gn as F,yn as G,j as H,vn as I,wn as J,En as K,bn as L,Ot as M,Sn as N,me as O,xe as P,Ut as Q,Mt as R,dt as S};
@@ -0,0 +1,4 @@
1
+ import{a as R}from"./chunk-T2X4E35X.js";import{a as x,k}from"./chunk-YN3SHWBR.js";import{a as b,b as w}from"./chunk-CL55MNGD.js";var y=class{capabilities=["text_generation","streaming","tool_calling","vision","audio","batch_processing","structured_output","reasoning"];provider="openai";modelId;client;config;constructor(t,o){this.client=t,this.config=o,this.modelId=o.model}async generateText(t,o){try{let n=g(this.config,t),s=await this.client.chat.completions.create(n,{signal:o,timeout:this.config.requestTimeoutMs});return b(C(s,this.modelId))}catch(n){return w(f(n))}}async*streamText(t,o){try{let n=g(this.config,t),s=await this.client.chat.completions.create({...n,stream:!0},{signal:o,timeout:this.config.requestTimeoutMs}),r=new Map,a=0,i=0,u=!1;for await(let c of s){let m=c.choices?.[0];if(m===void 0)continue;let d=m.delta;if(d?.content!==void 0&&d.content!==null&&(yield{kind:"content_delta",textDelta:d.content}),d?.refusal!==void 0&&d.refusal!==null&&d.refusal!==""&&(u=!0,yield{kind:"content_delta",textDelta:d.refusal}),d?.tool_calls!==void 0)for(let l of d.tool_calls){let p=l.index??0,_=r.get(p);_===void 0?r.set(p,{id:l.id??"",name:l.function?.name??"",args:l.function?.arguments??""}):_.args+=l.function?.arguments??""}if(m.finish_reason!==void 0&&m.finish_reason!==null){for(let[,l]of r){let p={};if(l.args!=="")try{p=JSON.parse(l.args)}catch{}yield{kind:"tool_call_delta",toolCall:{id:l.id,name:l.name,arguments:p}}}c.usage!==void 0&&(a=c.usage.prompt_tokens??0,i=c.usage.completion_tokens??0),yield{kind:"message_done",stopReason:u?"refusal":T(m.finish_reason),usage:{inputTokens:a,outputTokens:i,totalTokens:a+i}}}}}catch(n){yield{kind:"error",error:f(n)}}}async submitBatch(t,o){let s=t.items.map(a=>{let i=g(this.config,a.options);return JSON.stringify({custom_id:a.customId,method:"POST",url:"/v1/chat/completions",body:i})}).join(`
2
+ `),r=new Blob([s],{type:"application/jsonl"});try{let a=await this.client.files.create({file:r,purpose:"batch"},{signal:o}),i=await this.client.batches.create({input_file_id:a.id,endpoint:"/v1/chat/completions",completion_window:"24h"},{signal:o});return h(i)}catch(a){throw f(a)}}async getBatchJob(t,o){try{let n=await this.client.batches.retrieve(t,{signal:o});return h(n)}catch(n){throw f(n)}}async listBatchJobs(t,o){try{let n=await this.client.batches.list({limit:t?.limit,after:t?.after},{signal:o}),s=[];for(let r of n.data??[])s.push(h(r));return s}catch(n){throw f(n)}}async downloadBatchResults(t,o){let n=t.storage?.outputRef;if(n===void 0)return[];try{let a=(await(await this.client.files.content(n,{signal:o})).text()).split(`
3
+ `).filter(u=>u.length>0),i=[];for(let u of a){let c=JSON.parse(u);c.response?.status_code===200?i.push({customId:c.custom_id,result:C(c.response.body,this.modelId)}):i.push({customId:c.custom_id,error:c.error?.message??"Unknown error"})}return i}catch(s){throw f(s)}}async cancelBatchJob(t,o){try{await this.client.batches.cancel(t,{signal:o})}catch(n){throw f(n)}}async close(){}getRawClient(){return this.client}},I={provider:"openai",createModel:async e=>{let t=await import("./openai-YPM2E7QS.js"),o={};e.apiKey!==void 0&&(o.apiKey=e.apiKey),e.baseUrl!==void 0&&(o.baseURL=e.baseUrl);let n=new t.OpenAI(o);return new y(n,e)}},g=(e,t)=>{let o=S(t.messages,t.system),n={model:e.model,messages:o,max_tokens:t.maxTokens??e.maxTokens};return t.temperature!==void 0&&(n.temperature=t.temperature),t.topP!==void 0&&(n.top_p=t.topP),t.stopWords!==void 0&&(n.stop=t.stopWords),t.tools!==void 0&&(n.tools=t.tools.map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:s.parameters??{type:"object",properties:{}}}}))),t.toolChoice!==void 0&&(n.tool_choice=t.toolChoice),t.responseFormat!==void 0&&(t.responseFormat.type==="json_schema"?n.response_format={type:"json_schema",json_schema:{name:t.responseFormat.name??"response",schema:R(t.responseFormat,"openai"),strict:!0}}:t.responseFormat.type==="json_object"&&(n.response_format={type:"json_object"})),t.effort!==void 0?n.reasoning_effort=t.effort:t.thinkingBudget!==void 0&&(n.reasoning_effort=J(t.thinkingBudget)),n},S=(e,t)=>{let o=[];t!==void 0&&o.push({role:"system",content:t});for(let n of e){if(n.role==="system"){let r=[];for(let a of n.content)a.kind==="text"&&r.push(a.text);o.push({role:"system",content:r.join(`
4
+ `)});continue}if(n.role==="tool"){for(let r of n.content)r.kind==="tool_result"&&o.push({role:"tool",tool_call_id:r.toolResult.toolCallId,content:r.toolResult.content});continue}let s=n.content.filter(r=>r.kind!=="thinking").map(v);s.length===1&&s[0]?.type==="text"?o.push({role:n.role,content:s[0].text}):o.push({role:n.role,content:s})}return o},v=e=>{switch(e.kind){case"text":return{type:"text",text:e.text};case"image":{let t;if(e.image.url!==void 0)t=e.image.url;else if(e.image.data!==void 0)t=`data:${e.image.mimeType??"image/png"};base64,${B(e.image.data)}`;else return{type:"text",text:"[unsupported image]"};return{type:"image_url",image_url:{url:t,detail:e.image.detail??"auto"}}}case"audio":{if(e.audio.data!==void 0){let t=e.audio.mimeType??"audio/mpeg",o=P(t);return{type:"input_audio",input_audio:{data:B(e.audio.data),format:o}}}return{type:"text",text:"[unsupported audio format]"}}case"tool_call":return{type:"function",id:e.toolCall.id,function:{name:e.toolCall.name,arguments:JSON.stringify(e.toolCall.arguments)}};default:return{type:"text",text:`[unsupported content: ${e.kind}]`}}},C=(e,t)=>{let o=[],n="end_turn",s=e.choices?.[0];if(s!==void 0){s.message?.content!==void 0&&s.message.content!==null&&o.push({kind:"text",text:s.message.content});let r=s.message?.refusal,a=typeof r=="string"&&r!=="";if(a&&o.push({kind:"text",text:r}),s.message?.tool_calls!==void 0)for(let i of s.message.tool_calls){let u={};try{u=JSON.parse(i.function?.arguments??"{}")}catch{}o.push({kind:"tool_call",toolCall:{id:i.id,name:i.function?.name??"",arguments:u}})}n=a?"refusal":T(s.finish_reason)}return{content:o,stopReason:n,usage:{inputTokens:e.usage?.prompt_tokens??0,outputTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},modelId:t,rawResponse:e}},T=e=>{switch(e){case"stop":case null:case void 0:case"":return"end_turn";case"length":return"max_tokens";case"tool_calls":case"function_call":return"tool_use";case"content_filter":return"refusal";default:return"stop"}},h=e=>({id:e.id,status:A(e.status),createdAt:new Date(e.created_at*1e3),completedAt:e.completed_at!==void 0?new Date(e.completed_at*1e3):void 0,totalCount:e.request_counts?.total??0,doneCount:e.request_counts?.completed??0,failedCount:e.request_counts?.failed??0,storage:{type:"openai_file",inputRef:e.input_file_id,outputRef:e.output_file_id}}),A=e=>e==="completed"?"completed":e==="failed"?"failed":e==="cancelled"||e==="cancelling"?"cancelled":e==="in_progress"||e==="finalizing"?"processing":"pending",J=e=>e<=1e3?"low":e>=1e4?"high":"medium",P=e=>e.includes("mp3")||e.includes("mpeg")?"mp3":e.includes("wav")?"wav":e.includes("flac")?"flac":e.includes("ogg")?"ogg":"mp3",f=e=>{if(e instanceof x)return e;let t=e instanceof Error?e:new Error(String(e)),o=e?.status??e?.statusCode??500;return k("openai",o,t)},B=e=>{let t="";for(let o=0;o<e.length;o++)t+=String.fromCharCode(e[o]);return btoa(t)};export{y as a,I as b};
@@ -0,0 +1,4 @@
1
+ import{r as i}from"./chunk-SWP6BJR6.js";import{C as o}from"./chunk-M4U4Y3XQ.js";var m=i.eventsDir,g=i.eventsFile,E=async(s,e)=>{let a=`${s}/${i.eventsDir}`,n=`${s}/${i.eventsFile}`;await o.fs.mkdir(a,{recursive:!0}),await o.fs.writeTextFile(n,JSON.stringify(e)+`
2
+ `,{append:!0})},b=async(s,e)=>{let a=`${s}/${i.eventsFile}`,n;try{n=await o.fs.readTextFile(a)}catch{return[]}let r=n.trim().split(`
3
+ `).filter(t=>t.length>0).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null);return e?.since!==void 0&&(r=r.filter(t=>t.ts>e.since)),r.reverse(),e?.limit!==void 0&&e.limit>0&&(r=r.slice(0,e.limit)),r},d=10,v=s=>s.split(`
4
+ `).filter(e=>e.length>0).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}}),f=async s=>{let e=`${s}/${i.eventsFile}`,a=new TextDecoder,n=0;try{n=(await o.fs.stat(e)).size}catch{}return{poll:async()=>{let t;try{t=await o.fs.readFile(e)}catch{return[]}if(t.length<=n)return[];let l=t.lastIndexOf(d);if(l<n)return[];let c=t.subarray(n,l);return n=l+1,v(a.decode(c))}}},y=500,x=(s,e,a)=>{let n=f(s),r=!1,t=!1,l=setInterval(async()=>{if(!(r||t)){t=!0;try{let c=await(await n).poll();for(let p of c){if(r)return;try{e(p)}catch{}}}finally{t=!1}}},a?.intervalMs??y);return()=>{r=!0,clearInterval(l)}};export{E as a,b,x as c};
@@ -0,0 +1 @@
1
+ import{a as R,b as g,c as p,d as v,f as m,g as d,h as y}from"./chunk-CCYWFSXR.js";import{a as S}from"./chunk-T2X4E35X.js";import{a as c,e as T}from"./chunk-YN3SHWBR.js";import{a as w,b as f,d as _}from"./chunk-CL55MNGD.js";var x=class{capabilities=["text_generation","streaming","tool_calling","structured_output"];provider="claude-code";modelId;binary;config;constructor(e,n){this.binary=e,this.config=n,this.modelId=n.model}async generateText(e,n){let r;try{r=b(this.config,e,"json")}catch(i){if(i instanceof T)return f(i);throw i}let s=y(e.messages,e.system),o=g(this.binary,r,{signal:n,stdinData:s,cwd:this.config.properties?.cwd}),a=m(o.stderr);try{let i=[],l=new TextDecoder;for await(let j of o.stdout)i.push(l.decode(j,{stream:!0}));let u=await o.waitForExit(),A=await a,k=d("claude-code",u.code,A);if(k!==null)return f(k);let P=i.join("");return w(O(P,this.modelId))}finally{await p(o,a)}}async*streamText(e,n){if(e.responseFormat?.type==="json_schema"){yield*this.#e(e,n);return}let r=this.config.properties?.streamFormat??"text",s=b(this.config,e,r),o=y(e.messages,e.system),a=g(this.binary,s,{signal:n,stdinData:o,cwd:this.config.properties?.cwd}),i=m(a.stderr);try{r==="stream-json"?yield*this.#n(a,i):yield*this.#t(a,i)}catch(l){l instanceof c?yield{kind:"error",error:l}:yield{kind:"error",error:new c(l instanceof Error?l.message:String(l),{provider:"claude-code",cause:l instanceof Error?l:void 0})}}finally{await p(a,i)}}async*#e(e,n){let r=await this.generateText(e,n);if(_(r)){yield{kind:"error",error:r.error};return}for(let s of r.value.content)s.kind==="text"&&s.text!==""?yield{kind:"content_delta",textDelta:s.text}:s.kind==="tool_call"&&(yield{kind:"tool_call_delta",toolCall:s.toolCall});yield{kind:"message_done",stopReason:r.value.stopReason,usage:r.value.usage}}async*#t(e,n){let r=new TextDecoder,s=e.stdout.getReader();try{let l=await s.read();for(;l.done!==!0;){let u=r.decode(l.value,{stream:!0});u.length>0&&(yield{kind:"content_delta",textDelta:u}),l=await s.read()}}finally{s.releaseLock()}let o=await e.waitForExit(),a=await n,i=d("claude-code",o.code,a);i!==null?yield{kind:"error",error:i}:yield{kind:"message_done",stopReason:"end_turn",usage:{inputTokens:0,outputTokens:0,totalTokens:0}}}async*#n(e,n){for await(let a of v(e.stdout)){let i=D(a);i!==null&&(yield i)}let r=await e.waitForExit(),s=await n,o=d("claude-code",r.code,s);o!==null&&(yield{kind:"error",error:o})}close(){return Promise.resolve()}getRawClient(){return null}},N={provider:"claude-code",createModel:async t=>{let e=await R("claude",t);return new x(e,t)}},b=(t,e,n)=>{let r=[];n!=="text"&&r.push("--output-format",n),n==="stream-json"&&r.push("--verbose"),t.model!==""&&r.push("--model",t.model);let s=t.properties?.maxTurns;s!==void 0&&r.push("--max-turns",String(s));let o=t.properties?.allowedTools;if(o!==void 0)for(let l of o)r.push("--allowedTools",l);let a=t.properties?.args;a!==void 0&&r.push(...a),e.effort!==void 0&&r.push("--effort",e.effort);let i=F(e.responseFormat);return i!==null&&r.push("--json-schema",i),r},F=t=>t?.type!=="json_schema"?null:JSON.stringify(S(t,"claude-code")),O=(t,e)=>{let n=t.trim(),r=o=>({content:[{kind:"text",text:o}],stopReason:"end_turn",usage:{inputTokens:0,outputTokens:0,totalTokens:0},modelId:e});try{let o=JSON.parse(n);return Array.isArray(o)?E(o,e):h(o,e)}catch{}let s=[];for(let o of n.split(/\r?\n/)){let a=o.trim();if(a.length!==0)try{s.push(JSON.parse(a))}catch{}}return s.length>0?E(s,e):n.startsWith("{")||n.startsWith("[")?r(""):r(n)},E=(t,e)=>{let n=s=>s!==null&&typeof s=="object",r=t.find(s=>n(s)&&s.type==="result"&&(s.result!==void 0||s.structured_output!==void 0));if(r!==void 0)return h(r,e);for(let s=t.length-1;s>=0;s--){let o=t[s];if(n(o)&&o.type==="assistant"&&n(o.message))return h(o,e)}return{content:[{kind:"text",text:""}],stopReason:"end_turn",usage:{inputTokens:0,outputTokens:0,totalTokens:0},modelId:e}},h=(t,e)=>{let n=[];if(t.structured_output!==void 0&&t.structured_output!==null)n.push({kind:"text",text:JSON.stringify(t.structured_output)});else if(t.result!==void 0)n.push({kind:"text",text:String(t.result)});else if(t.message?.content!==void 0)for(let r of t.message.content)r.type==="text"?n.push({kind:"text",text:r.text}):r.type==="tool_use"&&n.push({kind:"tool_call",toolCall:{id:r.id??r.name,name:r.name,arguments:r.input??{}}});else typeof t=="string"&&n.push({kind:"text",text:t});return n.length===0&&n.push({kind:"text",text:""}),{content:n,stopReason:C(t.stop_reason??t.message?.stop_reason),usage:{inputTokens:t.usage?.input_tokens??0,outputTokens:t.usage?.output_tokens??0,totalTokens:(t.usage?.input_tokens??0)+(t.usage?.output_tokens??0)},modelId:e,rawResponse:t}},C=t=>t==="tool_use"?"tool_use":t==="refusal"?"refusal":"end_turn",D=t=>{if(t===null||typeof t!="object")return null;let e=t;if(e.type==="assistant"){if(e.message?.content!==void 0){for(let n of e.message.content)if(n.type==="text")return{kind:"content_delta",textDelta:n.text}}return null}return e.type==="content_block_delta"?e.delta?.type==="text_delta"?{kind:"content_delta",textDelta:e.delta.text}:null:e.type==="result"?{kind:"message_done",stopReason:e.subtype==="tool_use"?"tool_use":C(e.stop_reason),usage:{inputTokens:e.usage?.input_tokens??0,outputTokens:e.usage?.output_tokens??0,totalTokens:(e.usage?.input_tokens??0)+(e.usage?.output_tokens??0)}}:e.type==="error"?{kind:"error",error:new c(e.error?.message??"Unknown Claude Code error",{provider:"claude-code"})}:e.content!==void 0&&typeof e.content=="string"?{kind:"content_delta",textDelta:e.content}:null};export{x as a,N as b,b as c,O as d};
@@ -0,0 +1,3 @@
1
+ import{d as re}from"./chunk-CCYWFSXR.js";import{a as F,c as N,d as U,e as j,f as D}from"./chunk-ZAY6LSJD.js";import{j as L}from"./chunk-ZW5C5IGT.js";import{a as te}from"./chunk-T2X4E35X.js";import{a as k}from"./chunk-YN3SHWBR.js";import{a as ee,b as I,g as R}from"./chunk-CL55MNGD.js";var l=class extends Error{statusCode;request;response;body;retryAfter;constructor(e,r){super(e,{cause:r?.cause}),this.name="HttpClientError",this.statusCode=r?.statusCode??null,this.request=r?.request??null,this.response=r?.response??null,this.body=r?.body,this.retryAfter=r?.retryAfter??null}},T=class extends l{code="RESPONSE_ERROR";constructor(e,r){super(e,r),this.name="HttpResponseError"}},P=class extends l{code="TIMEOUT";constructor(e,r){super(e,r),this.name="HttpTimeoutError"}},S=class extends l{code="ABORT_ERROR";constructor(e,r){super(e,r),this.name="HttpAbortError"}},_=class extends l{code="RATE_LIMITED";constructor(e,r){super(e,r),this.name="HttpRateLimitError"}},H=class extends l{code="NETWORK_ERROR";constructor(e,r){super(e,r),this.name="HttpNetworkError"}},se=t=>t===429?_:t>=500&&t<=599||t===408?T:null,B=(t,e)=>{if(t instanceof l)return t;if(t.name==="TimeoutError")return new P(t.message,{cause:t,...e!==void 0&&{statusCode:e.status,response:e}});if(t.name==="AbortError")return new S(t.message,{cause:t});if(e!==void 0){let r=se(e.status),s={statusCode:e.status,response:e,cause:t};return r!==null?new r(t.message,s):new T(t.message,s)}return t.message.includes("Failed to fetch")||t.message.includes("fetch failed")||t.message.includes("ECONNREFUSED")||t.message.includes("ENOTFOUND")?new H(t.message,{cause:t}):new l(t.message,{cause:t})};var $=async(t,e)=>{let r=t;for(let s of e)r=await s.intercept(r);return r},J=async(t,e)=>{let r=t;for(let s of e)r=await s.intercept(r);return r};var q=class extends Error{status;statusText;headers;body;retries;constructor(e){super(e.error),this.name="GoHttpError",this.status=e.status??0,this.statusText=e.statusText??"",this.headers=e.headers??{},this.body=e.body??"",this.retries=e.retries??0}},He=3e4,oe=async(t,e,r)=>{let{signal:s,...n}=e;if(s===void 0)return await r({handle:t,...n},{});s.throwIfAborted();let o=L(s);try{return await r({handle:t,...n,requestId:o.requestId},{signal:s})}finally{o.release()}},xe=t=>{let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r},ie=t=>{let e=t.timeoutMs??He;if(!Number.isFinite(e)||e<=0)throw new RangeError(`createGoHttpClient: timeoutMs ${e} is not a positive number of milliseconds`);return e},Ce=(t,e={})=>{let r=ie(e),s=t.call("httpCreate",{...e,timeoutMs:r});if(s.error!==void 0&&s.error!=="")throw new Error(`createGoHttpClient: ${s.error}`);let n=s.handle??"";return{async request(o){let i=await oe(n,o,(a,d)=>t.call("httpRequest",a,d));if(i.error!==void 0&&i.error!=="")throw new q({...i,error:i.error});return i},async requestStream(o){let i=await oe(n,o,(b,m)=>t.stream("httpRequestStream",b,m)),a=i.opened;if(a.error!==void 0&&a.error!==""||i.handle==="")throw new q({error:a.error??"open HTTP stream: the Go bridge returned no stream handle",status:a.status,statusText:a.statusText,headers:a.headers,body:a.body});let d=a.status??200,f=a.statusText??"",c={...a.headers},u=!1,y=()=>{u||(u=!0,i.close())};return{body:new ReadableStream({async pull(b){let m=await i.read({signal:o.signal});if(m===null){y(),b.close();return}if(m.error!==void 0&&m.error!==""){y(),b.error(new Error(m.error));return}m.chunk!==void 0&&m.chunk!==""&&b.enqueue(xe(m.chunk)),m.done===!0&&(y(),b.close())},cancel(){y()}}),status:d,statusText:f,headers:c}},close(){t.call("httpClose",n)}}},ae=async(t={})=>{ie(t),await F();let e=N();if(e===null)throw new Error(`createGoHttpClient: the @eserstack/ajan native library is not available${j()}`,{cause:U()??void 0});return Ce(e,t)};var Ee=new Set([204,205,304]),X=(t,e,r,s)=>new Response(Ee.has(t)?null:s,{status:t,statusText:e,headers:r}),we=(t,e)=>{if(t instanceof q){if(t.status>=400)return X(t.status,t.statusText,t.headers,t.body);if(t.status===0)throw new H(`${e.method} request through the native client: ${t.message}`,{cause:t})}let r=t instanceof Error?t:new Error(String(t));throw new l(`${e.method} request through the native client: ${r.message}`,{cause:r})},ue=(t,e)=>async r=>{r.signal.throwIfAborted();let s=r.body===null?"":await r.text(),n={method:r.method,url:r.url,headers:Object.fromEntries(r.headers),...s!==""&&{body:s},signal:r.signal};try{if(e){let i=await t.requestStream(n);return X(i.status,i.statusText,i.headers,i.body)}let o=await t.request(n);return X(o.status,o.statusText,o.headers,o.body)}catch(o){if(r.signal.aborted)throw r.signal.reason;return we(o,r)}};var ce=t=>Number.isFinite(t)?t:String(t),de=t=>typeof t=="number"?t:Number(t),A=t=>typeof t=="number"?ce(t):t,pe=t=>{if(t===void 0||t===!1||typeof t!="object"||t===null)return t;let e=t.retryableStatuses;return{maxAttempts:A(t.maxAttempts),initialDelay:A(t.initialDelay),maxDelay:A(t.maxDelay),factor:A(t.factor),jitter:t.jitter,retryableStatuses:Array.isArray(e)?e.map(r=>A(r)):e,respectRetryAfter:t.respectRetryAfter}},me=()=>{try{return D()}catch(t){let e=t instanceof Error?t:new Error(String(t));throw new l(`HttpClient runs its retry policy in Go through @eserstack/ajan: ${e.message}`,{cause:e})}},V=t=>new l(`HttpClient: the retry policy refused the request: ${t}; check the retry settings against RetryConfig`),fe=(t,e,r)=>{let s=me().call("httpRetryResolve",{client:pe(t),request:pe(e),streamBody:r});if(typeof s.error=="string"&&s.error!=="")throw V(s.error);if(s.plan===void 0)throw V("the answer has no plan");return{maxAttempts:de(s.plan.maxAttempts),wire:s.plan}},z=(t,e,r,s)=>{let n=me().call("httpRetryNext",{plan:t.wire,attempt:e,status:r,retryAfterMs:s===null?null:ce(s),random:Math.random()});if(typeof n.error=="string"&&n.error!=="")throw V(n.error);return{retry:n.retry===!0,delayMs:de(n.delayMs??0)}};var ye=3e4,qe=t=>new Promise(e=>setTimeout(e,t)),Oe=(t,e)=>{if(e.startsWith("http://")||e.startsWith("https://"))return e;if(t!==void 0&&t!==""){let r=t.replace(/\/$/,""),s=e.startsWith("/")?e:`/${e}`;return`${r}${s}`}return e};var ge=t=>{if(t===null)return null;let e=Number(t);if(!Number.isNaN(e)&&e>=0)return Math.round(e*1e3);let r=new Date(t);return Number.isNaN(r.getTime())?null:Math.max(0,r.getTime()-Date.now())},he=t=>{let e=t.get("X-RateLimit-Remaining")??t.get("x-rate-limit-remaining"),r=t.get("X-RateLimit-Limit")??t.get("x-rate-limit-limit"),s=t.get("X-RateLimit-Reset")??t.get("x-rate-limit-reset"),n=t.get("Retry-After");if(e===null&&r===null&&s===null&&n===null)return;let o=ge(n);return{...e!==null&&{remaining:Number(e)},...r!==null&&{limit:Number(r)},...s!==null&&{resetAt:Number(s)},...o!==null&&{retryAfterSeconds:o/1e3}}},ke=async t=>{try{return await t.clone().json()}catch{return await t.clone().text().catch(()=>{})}},Ae=t=>{if(typeof t=="object"&&t!==null){let e=t,r=e.error??e.message??e.detail??e.title;if(r!==void 0)return String(r)}return null},G=class t{config;#e=null;constructor(e){if(e?.transport==="native"&&e.fetchFn!==void 0)throw new TypeError('HttpClient: fetchFn and transport "native" exclude each other; pass one of them');this.config=e??{}}withDefaults(e){return new t({...this.config,...e,headers:{...this.config.headers??{},...e.headers??{}}})}request(e,r,s){return this._execute(e,r,s)}get(e,r){return this._execute("GET",e,r)}post(e,r){return this._execute("POST",e,r)}put(e,r){return this._execute("PUT",e,r)}patch(e,r){return this._execute("PATCH",e,r)}delete(e,r){return this._execute("DELETE",e,r)}requestStream(e,r,s){return this._executeStream(e,r,s)}postStream(e,r){return this.requestStream("POST",e,r)}requestResult(e,r,s){return R(this._execute(e,r,s),x)}getResult(e,r){return R(this._execute("GET",e,r),x)}postResult(e,r){return R(this._execute("POST",e,r),x)}putResult(e,r){return R(this._execute("PUT",e,r),x)}patchResult(e,r){return R(this._execute("PATCH",e,r),x)}deleteResult(e,r){return R(this._execute("DELETE",e,r),x)}requestStreamResult(e,r,s){return R(this._executeStream(e,r,s),x)}postStreamResult(e,r){return R(this._executeStream("POST",e,r),x)}async _executeFetch(e,r,s,n,o){let i=this.config._delayFn??qe,a=Oe(this.config.baseUrl,r),d=new URL(a);if(s?.params!==void 0)for(let[C,p]of Object.entries(s.params))d.searchParams.set(C,p);let f={...this.config.headers??{},...s?.headers??{}},c,u=s?.body;if(u!==void 0&&(typeof u=="string"||u instanceof ArrayBuffer||ArrayBuffer.isView(u)||u instanceof Blob||u instanceof FormData||u instanceof URLSearchParams||u instanceof ReadableStream?c=u:typeof u=="object"&&u!==null&&(c=JSON.stringify(u),f["Content-Type"]===void 0&&(f["Content-Type"]="application/json"))),this.config.transport==="native"&&c!==void 0&&typeof c!="string"&&!(c instanceof URLSearchParams))throw new l(`${e} request: transport "native" sends text bodies only (a string, URLSearchParams, or an object sent as JSON); send binary, form and stream bodies with the default fetch transport`);let y=!(c instanceof ReadableStream),O=fe(this.config.retry,s?.retry,!y),b=s?.timeout??this.config.timeout??ye,m=this.config.interceptors?.request??[],be=await this.#t(n),Q=0;for(let C=0;C<O.maxAttempts;C++){C>0&&Q++;let p,M;try{let g=s?.signal,E=AbortSignal.timeout(b),h=g!==void 0?AbortSignal.any([E,g]):E,w={method:e,headers:f,body:c,signal:h,...!y&&{duplex:"half"}},v=new Request(d.toString(),w);M=await $(v,m),p=await be(M)}catch(g){let E=g instanceof Error?g:new Error(String(g)),h=B(E);if(h instanceof P||h instanceof S)throw h;let w=z(O,C,0,null);if(!w.retry)throw h;await i(w.delayMs);continue}let Z=he(p.headers);if(!p.ok){let g=await ke(p),E=Ae(g)??`HTTP ${p.status}`,h=Z!==void 0?ge(p.headers.get("Retry-After")):null,w=p.status===429?new _(E,{statusCode:p.status,response:p,body:g,...h!==null&&{retryAfter:h/1e3}}):new T(E,{statusCode:p.status,response:p,body:g}),v=z(O,C,p.status,h);if(v.retry){await i(v.delayMs);continue}throw w}return await o(p,M,Q,Z)}throw new l(`Request failed after ${O.maxAttempts} attempt(s)`)}_execute(e,r,s){let n=this.config.interceptors?.response??[];return this._executeFetch(e,r,s,!1,async(o,i,a,d)=>{let f;if(o.status===204||o.status===304||o.headers.get("Content-Length")==="0")f=void 0;else if((o.headers.get("Content-Type")??"").includes("application/json"))f=await o.json();else{let y=await o.text();try{f=JSON.parse(y)}catch{f=y}}let c={data:f,status:o.status,statusText:o.statusText,headers:o.headers,request:i,raw:o,retries:a,...d!==void 0&&{rateLimit:d}};return c=await J(c,n),c})}_executeStream(e,r,s){return this._executeFetch(e,r,s,!0,(n,o,i,a)=>n.body===null?Promise.reject(new H("Response body is null \u2014 server sent no body for a streaming request")):Promise.resolve({body:n.body,status:n.status,statusText:n.statusText,headers:n.headers,request:o,raw:n,retries:i,...a!==void 0&&{rateLimit:a}}))}async#t(e){return this.config.transport!=="native"?this.config.fetchFn??fetch:ue(await this.#r(),e)}#r(){if(this.#e!==null)return this.#e;let r=(this.config._createGoClient??ae)({timeoutMs:this.config.timeout??ye}).catch(s=>{throw new l('transport "native": the Go HTTP client could not be created; remove transport: "native" to send requests with fetch',{cause:s instanceof Error?s:new Error(String(s))})});return this.#e=r,r}close(){let e=this.#e;this.#e=null,e?.then(r=>r.close(),()=>{})}},K=t=>new G(t),x=t=>{if(t instanceof l)return t;let e=t instanceof Error?t:new Error(String(t));return new l(e.message,{cause:e})};var Ge="http://localhost:11434",Y=class{capabilities=["text_generation","streaming","vision"];provider="ollama";modelId;_baseUrl;_client;config;constructor(e,r){this._baseUrl=e,this._client=K({baseUrl:e,retry:!1}),this.config=r,this.modelId=r.model}async generateText(e,r){try{let s=Re(this.config,e,!1),n=await this._client.post("/api/chat",{body:s,signal:r});return ee(Ie(n.data,this.modelId))}catch(s){if(s instanceof k)return I(s);let n=s instanceof l?s.statusCode??void 0:void 0;return I(new k(s instanceof Error?s.message:String(s),{provider:"ollama",statusCode:n,cause:s instanceof Error?s:void 0}))}}async*streamText(e,r){try{let s=Re(this.config,e,!0),n=await this._client.postStream("/api/chat",{body:s,signal:r});for await(let o of re(n.body)){let i=Le(o);i!==null&&(yield i)}}catch(s){if(s instanceof k)yield{kind:"error",error:s};else{let n=s instanceof l?s.statusCode??void 0:void 0;yield{kind:"error",error:new k(s instanceof Error?s.message:String(s),{provider:"ollama",statusCode:n,cause:s instanceof Error?s:void 0})}}}}close(){return Promise.resolve()}getRawClient(){return null}},Ke={provider:"ollama",createModel(t){let e=t.properties?.baseUrl??Ge;return Promise.resolve(new Y(e,t))}},Re=(t,e,r)=>{let s=Me(e.messages,e.system),n={model:t.model,messages:s,stream:r},o={};return e.temperature!==void 0&&(o.temperature=e.temperature),e.maxTokens!==void 0&&(o.num_predict=e.maxTokens),e.topP!==void 0&&(o.top_p=e.topP),e.stopWords!==void 0&&(o.stop=e.stopWords),Object.keys(o).length>0&&(n.options=o),e.responseFormat!==void 0&&(e.responseFormat.type==="json_schema"?n.format=te(e.responseFormat,"ollama"):e.responseFormat.type==="json_object"&&(n.format="json")),n},Me=(t,e)=>{let r=[];e!==void 0&&r.push({role:"system",content:e});for(let s of t){if(s.role==="system"){let a=[];for(let d of s.content)d.kind==="text"&&a.push(d.text);r.push({role:"system",content:a.join(`
2
+ `)});continue}let n=[],o=[];for(let a of s.content)a.kind==="text"?n.push(a.text):a.kind==="image"&&a.image.url!==void 0&&o.push(a.image.url);let i={role:s.role==="tool"?"user":s.role,content:n.join(`
3
+ `)};o.length>0&&(i.images=o),r.push(i)}return r},Ie=(t,e)=>{let r=[];return t.message?.content!==void 0&&r.push({kind:"text",text:t.message.content}),{content:r,stopReason:t.done_reason==="length"?"max_tokens":"end_turn",usage:{inputTokens:t.prompt_eval_count??0,outputTokens:t.eval_count??0,totalTokens:(t.prompt_eval_count??0)+(t.eval_count??0)},modelId:e,rawResponse:t}},Le=t=>{if(t===null||typeof t!="object")return null;let e=t;return e.done===!0?{kind:"message_done",stopReason:e.done_reason==="length"?"max_tokens":"end_turn",usage:{inputTokens:e.prompt_eval_count??0,outputTokens:e.eval_count??0,totalTokens:(e.prompt_eval_count??0)+(e.eval_count??0)}}:e.message?.content!==void 0&&e.message.content.length>0?{kind:"content_delta",textDelta:e.message.content}:e.response!==void 0&&e.response.length>0?{kind:"content_delta",textDelta:e.response}:null};export{Y as a,Ke as b};
@@ -0,0 +1,3 @@
1
+ import{b as w}from"./chunk-D2UKX2VW.js";import{n as A,o as v,r as g}from"./chunk-SWP6BJR6.js";import{C as f}from"./chunk-M4U4Y3XQ.js";var T=r=>{let t=r.split(/\n/).flatMap(i=>i.trim().length>0?[i.trim()]:[]);return t.length>1?t:r.split(/\.(?=\s+[A-Z])|;\s+/).map(i=>i.trim()).filter(i=>i.length>5)},D=(r,t=[])=>{let i=[],a=r.find(o=>o.questionId==="ambition");if(a!==void 0){let o=a.answer,c=o.match(/10[- ]?star[:\s]+(.+?)(?:\n|$)/is),u=o.match(/5[- ]?star[:\s]+(.+?)(?:\n|$)/is),n=(c!==null?c[1].trim():u!==null?u[1].trim():o.replace(/1[- ]?star[:\s]+[^.]*\.\s*/i,"").trim()).replace(/^(the|a|an|with|plus|also)\s+/i,"").replace(/^(the\s+)?(target|goal|objective)[:\s]+/i,"").trim();n.length>0&&(n=n.charAt(0).toUpperCase()+n.slice(1)),n=n.replace(/[.\u2026]+$/,"").trim(),n.length>140&&(n=n.slice(0,137)+"..."),n.length>3&&i.push(n)}let l=r.find(o=>o.questionId==="verification");if(l!==void 0){let o=l.answer.split(/\n/).map(c=>c.replace(/^\s*[-\u2022*]\s*/,"").trim()).filter(c=>c.length>0);for(let c of o)i.push(c)}for(let o of t){let c=o.choice.toLowerCase();if(c.includes("accepted")||c.includes("add to scope")){let u=o.question.replace(/^should\s+(we|i)\s+/i,"").replace(/\?+$/,"").trim(),e=u.charAt(0).toUpperCase()+u.slice(1);i.push(e)}}return i.length===0&&i.push("_Tasks need to be defined before execution. Add tasks manually or run discovery with more detail._"),i.push("Write or update tests for all new and changed behavior"),i.push("Update documentation for all public-facing changes (README, API docs, CHANGELOG)"),i},k=(r,t)=>typeof t=="string"?{id:`${r}-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}`,title:t,placeholder:"_To be addressed during execution._",scope:[],condition:null}:{id:t.id,title:t.title,placeholder:t.placeholder,scope:t.scope??[],condition:t.condition??null},I=(r,t)=>A(r)?t===null?!1:v(r,t):!0,b=(r,t,i,a,l,o,c,u)=>{let e=[];e.push(`# Spec: ${r}`),e.push(""),e.push("## Status: draft"),e.push(""),i.length>0&&(e.push(`## Concerns: ${i.map(s=>s.id).join(", ")}`),e.push("")),e.push("## Discovery Answers"),e.push("");for(let s of t){if(e.push(`### ${s.questionId}`),e.push(""),e.push(s.answer),"user"in s&&s.user!=="Unknown User"){let p=s;e.push(""),e.push(`_-- ${p.user}_`)}e.push("")}for(let s of i)if(s.specSections.length>0)for(let p of s.specSections){let h=k(s.id,p);I(h,l??null)&&(e.push(`## ${h.title} (${s.id})`),e.push(""),e.push(h.placeholder),e.push(""))}for(let s of i){let p=s.registries??[];if(p.length===0)continue;let h=s.reviewDimensions??[];for(let d of p){let m=h.find(x=>x.id===d);m!==void 0&&(e.push(`## ${m.label} (${s.id})`),e.push(""),e.push(`_${m.prompt}_`),e.push(""),d==="error-rescue"?(e.push("| Codepath | What Can Go Wrong | Exception Class | Rescued? | Recovery Action | User Sees |"),e.push("|----------|-------------------|-----------------|----------|----------------|-----------|"),e.push("| _To be filled during execution._ | | | | | |")):d==="failure-modes"?(e.push("| Codepath | Failure Mode | Rescued? | Tested? | User Sees | Logged? |"),e.push("|----------|--------------|----------|---------|-----------|---------|"),e.push("| _To be filled during execution._ | | | | | |")):d==="test-plan"?(e.push("| Behavior | Test Layer | Happy Path | Failure Path | Edge Case |"),e.push("|----------|------------|------------|--------------|-----------|"),e.push("| _To be filled during execution._ | | | | |")):e.push("_To be filled during execution._"),e.push(""))}}if(a.length>0){e.push("## Decisions"),e.push(""),e.push("| # | Decision | Choice | Promoted |"),e.push("|---|----------|--------|----------|");for(let s=0;s<a.length;s++){let p=a[s];e.push(`| ${s+1} | ${p.question} | ${p.choice} | ${p.promoted?"yes":"no"} |`)}e.push("")}let n=t.find(s=>s.questionId==="scope_boundary");if(n!==void 0){e.push("## Out of Scope"),e.push("");let s=T(n.answer);for(let p of s)e.push(`- ${p}`);e.push("")}let $=D(t,a);e.push("## Tasks"),e.push("");for(let s=0;s<$.length;s++)e.push(`- [ ] task-${s+1}: ${$[s]}`);e.push("");let y=t.find(s=>s.questionId==="verification");if(e.push("## Verification"),e.push(""),y!==void 0){let s=T(y.answer);for(let p of s)e.push(`- ${p}`)}else e.push("_To be defined._");e.push("");let S=o??[];if(S.length>0){e.push("## Custom Acceptance Criteria"),e.push("");for(let s of S)e.push(`- ${s.text} _-- ${s.user}, ${s.addedInPhase}_`);e.push("")}let C=(c??[]).filter(s=>!s.text.startsWith("[TASK] "));if(C.length>0){e.push("## Notes"),e.push("");for(let s of C)e.push(`- ${s.text} _-- ${s.user}, ${s.phase}_`);e.push("")}let _=u??[];if(_.length>0){e.push("## Transition History"),e.push(""),e.push("| From | To | User | Timestamp | Reason |"),e.push("|------|----|------|-----------|--------|");for(let s of _)e.push(`| ${s.from} | ${s.to} | ${s.user} | ${s.timestamp} | ${s.reason??"-"} |`);e.push("")}return e.join(`
2
+ `)};var z=async(r,t,i)=>{if(t.spec===null)throw new Error("No active spec");let a=`${r}/${g.specDir(t.spec)}`,l=`${r}/${g.specFile(t.spec)}`;await f.fs.mkdir(a,{recursive:!0});let o=b(t.spec,t.discovery.answers,i,t.decisions,t.classification,t.customACs,t.specNotes,t.transitionHistory);await f.fs.writeTextFile(l,o);let c=w(t.spec,o),u=`${a}/progress.json`,e={spec:t.spec,status:"draft",tasks:c.tasks.map(n=>({id:n.id,title:n.title,status:"pending"})),decisions:t.decisions.map(n=>({question:n.question,choice:n.choice,promoted:n.promoted})),debt:[],updatedAt:new Date().toISOString()};return await f.fs.writeTextFile(u,JSON.stringify(e,null,2)+`
3
+ `),l};export{z as a};
@@ -0,0 +1,2 @@
1
+ import{C as t,b as i,n as a}from"./chunk-M4U4Y3XQ.js";var m=448,l=384,s=e=>{let r=t.env.get(e);return r===void 0||r===""?null:r},c=()=>{let e=s("XDG_CONFIG_HOME");if(e!==null)return`${e}/eser/noskills`;let r=s("HOME")??s("USERPROFILE");if(r===null)throw new Error("cannot find the noskills config directory: set HOME, USERPROFILE or XDG_CONFIG_HOME");return`${r}/.config/eser/noskills`},o=()=>`${c()}/user.json`,u=async e=>{try{let r=await t.fs.readTextFile(o()),n=JSON.parse(r);return typeof n.name!="string"||n.name.length===0?null:{name:n.name,email:n.email??""}}catch{return null}},w=async e=>{let r=c(),n=o();await t.fs.mkdir(r,{recursive:!0,mode:m}),await t.fs.writeTextFile(n,JSON.stringify({name:e.name,email:e.email},null,2)+`
2
+ `,{mode:l}),a()!=="windows"&&await t.fs.chmod(n,l)},x=async()=>{let e=o();try{return await t.fs.remove(e),!0}catch(r){if(r instanceof i)return!1;let n=r instanceof Error?r.message:String(r);throw new Error(`remove the user identity ${e}: ${n}`,{cause:r})}},f=async()=>{try{let e=(await t.exec.exec("git",["config","user.name"])).trim(),r=(await t.exec.exec("git",["config","user.email"])).trim();return e.length===0?null:{name:e,email:r}}catch{return null}},E=e=>e.email.length>0?`${e.name} <${e.email}>`:e.name,h=e=>e.name,g=()=>({name:"Unknown User",email:""}),p=async e=>{let r=await u();if(r!==null)return r;let n=await f();return n!==null?n:g()};export{o as a,u as b,w as c,x as d,f as e,E as f,h as g,p as h};
@@ -0,0 +1 @@
1
+ var y=new Set(["log","diff","status","show","blame","rev-parse","ls-files","ls-tree","cat-file","describe","shortlog","name-rev","for-each-ref","rev-list","help","version"]),I=new Map([["branch",new Set(["","--list","-l","-a","--all","-r","--remotes","-v","--verbose","--contains","--no-contains","--merged","--no-merged","--show-current"])],["tag",new Set(["","-l","--list","-v","--verify","-n"])],["stash",new Set(["list","show"])],["remote",new Set(["","-v","--verbose","show","get-url"])],["reflog",new Set(["","show"])]]),m=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),R=new Set(["--exec-path"]),O=new Set(["--no-replace-objects","--no-lazy-fetch","--no-advice","--bare","--no-optional-locks","--literal-pathspecs","--glob-pathspecs","--noglob-pathspecs","--icase-pathspecs","--no-pager","-P","--paginate","-p"]),L=new Set(["--version","-v","--help","-h","--exec-path","--html-path","--man-path","--info-path"]),T=new Set(["push","send-pack"]),E=new Set(["--get","--get-all","--get-regexp","--get-urlmatch","--get-color","--get-colorbool","--list","-l"]),v=new Set(["get","list"]),C=new Set(["--global","--local","--system","--worktree","--show-origin","--show-scope","--name-only","--null","-z","--includes","--no-includes","--bool","--int","--bool-or-int","--path","--expiry-date","--no-type","--fixed-value","--all"]),S=new Set(["--file","-f","--blob","--type","--default","--url"]),N=e=>{let t=!1,n=[];for(let s=0;s<e.length;s++){let o=e[s];if(E.has(o)){t=!0;continue}if(!C.has(o)){if(S.has(o)){s+=1;continue}if(o.startsWith("--")&&o.includes("=")){let i=o.slice(0,o.indexOf("="));if(S.has(i))continue;return!1}if(o.startsWith("-"))return!1;n.push(o)}}if(t)return!0;let[r]=n;return r!==void 0&&v.has(r)?!0:n.length===1},W=e=>{let t=e.indexOf("=");if(!e.startsWith("--")||t===-1)return!1;let n=e.slice(0,t);return m.has(n)||R.has(n)},F=e=>{let t=0;for(;t<e.length;){let n=e[t];if(m.has(n)){t+=2;continue}if(O.has(n)){t+=1;continue}if(W(n)){t+=1;continue}if(n.startsWith("-C")&&n.length>2){t+=1;continue}if(n.startsWith("-c")&&n.length>2&&n.includes("=")){t+=1;continue}return t}return-1},c=e=>e.replace(/["'\\]/g,""),w=e=>{let t=c(e),n=(t.split(/[/\\]/).pop()??t).toLowerCase();return n==="git"||n==="git.exe"},$=new Set(["env","command","exec","sudo","nohup","time","nice","builtin"]),M=/^[A-Za-z_][A-Za-z0-9_]*=/,f=e=>{let t=0;for(;t<e.length;){let n=c(e[t]);if(M.test(n)){t+=1;continue}if($.has(n.toLowerCase())){for(t+=1;t<e.length&&e[t].startsWith("-");)t+=1;continue}return t}return-1},b=e=>/^\$(?:[A-Za-z_][A-Za-z0-9_]*|\{[^}]+\})$/.test(c(e)),g=e=>{let t=e.trim();if(t.length===0)return!0;let n=t.split(/\s+/),r=f(n);if(r===-1)return!0;let s=n.slice(r);return b(s[0])&&s.length>1?!1:w(s[0])?D(s.slice(1).map(c)):!0},x=e=>{let t=F(e);return t===-1?{globalOptions:e,subcommand:"",subcommandArgs:[]}:{globalOptions:e.slice(0,t),subcommand:e[t],subcommandArgs:e.slice(t+1)}},D=e=>{let{subcommand:t,subcommandArgs:n}=x(e);if(t===""||y.has(t)||L.has(t))return!0;if(t==="config")return N(n);let r=I.get(t);if(r!==void 0){let s=n[0]??"";if(r.has(s))return!0}return!1},U=e=>T.has(x(e).subcommand);var _=e=>{let t=[],n=e.split(/&&|\|\||;|\n/);for(let r of n){let s=r.trim();if(s.length===0)continue;let o=s.split(/\s+/),i=f(o);if(i!==-1){let l=o[i];if(c(l)!==l&&w(l)||b(l)){let p=o.slice(i).join(" ");t.push((p.split(/[|&;)`]/)[0]??p).trim())}}if(!/git/i.test(s))continue;let a=s.matchAll(/(?:^|[\s($`/\\])git\b/gi);for(let l of a){let p=l[0].toLowerCase().indexOf("git"),G=(l.index??0)+p,h=s.slice(G),d=(h.split(/[;&|$)`'"]/)[0]??h).trim();d.toLowerCase().startsWith("git")&&t.push(d)}}return t},z=e=>{let t=[/(?:^|\s)(?:\S*\/)?[a-z]*sh\s+-\w*c\s+\$?["'](.+?)["']/g,/(?:^|\s)(?:\S*\/)?[a-z]*sh\s+-\w*c\s+(\S+)/g,/eval\s+["'](.+?)["']/g];for(let s of t){let o;for(;(o=s.exec(e))!==null;){let i=o[1]??"";if(i.includes("git")&&!g(i))return!0}}let n=e.split("|");for(let s of n){let o=s.trim();if(o.length>0&&!g(o))return!0}let r=e.matchAll(/(?:^|[\s($`/\\])git\b/gi);for(let s of r){let i=s[0].toLowerCase().indexOf("git"),a=(s.index??0)+i,u=(e.slice(a).split(/[;&|$)`'"]/)[0]??"").trim();if(u.toLowerCase().startsWith("git")&&!g(u))return!0}if(B(e)){let s=e.replace(/["'\\]/g,"");for(let o of _(s))if(!g(o))return!0}return!1},A=String.raw`(?:\S*\/)?(?:ba|z|k|da|a)?sh`,P=new RegExp(String.raw`\|\s*${A}(?:\s+-\w+)*\s*(?:$|[;&|)])`,"m"),k=new RegExp(String.raw`(?:^|[\s;&|(])${A}(?:\s+-\w+)*\s*<<`,"m"),B=e=>P.test(e)||k.test(e),Z=e=>{let t=[],n=e.split(/&&|\|\||;|\n|\|/);for(let r of n){let s=r.trim().split(/\s+/).map(c),o=f(s);if(o===-1)continue;let i=(s[o].split("/").pop()??"").toLowerCase(),a=o+1;if(/^(?:ba|z|k|da|a)?sh$/.test(i))for(;a<s.length&&s[a].startsWith("-");){if(/c/.test(s[a])){a=-1;break}a+=1}else if(i!=="source"&&i!==".")continue;a>=0&&a<s.length&&!s[a].startsWith("<")&&t.push(s[a])}return t},q=(e,t)=>{let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(String.raw`(?:>>?|\btee(?:\s+-a)?)\s*["']?${n}["']?(?:\s|$|[;&|])`).test(e)},H=e=>e.replace(/--\w+='[^']*'/g,"").replace(/--\w+="[^"]*"/g,"").replace(/--\w+=\S*/g,""),j=e=>{let t=H(e);for(let n of _(t))if(!g(n))return!0;return z(t)};export{y as a,I as b,m as c,R as d,O as e,L as f,T as g,g as h,x as i,D as j,U as k,_ as l,z as m,Z as n,q as o,H as p,j as q};
@@ -0,0 +1,39 @@
1
+ import{C as I}from"./chunk-M4U4Y3XQ.js";import{d as H}from"./chunk-HISXAZ4Y.js";var y=e=>e.map(r=>typeof r=="string"?oe(r):r),oe=e=>({kind:"text",value:e});var me=(...e)=>({kind:"bold",children:y(e)}),ye=(...e)=>({kind:"dim",children:y(e)});var he=(...e)=>({kind:"group",children:y(e)});var g=(e,...r)=>({kind:"color",color:e,children:y(r)}),fe=(...e)=>g("red",...e),Se=(...e)=>g("green",...e),ke=(...e)=>g("yellow",...e),xe=(...e)=>g("blue",...e),we=(...e)=>g("magenta",...e),ge=(...e)=>g("cyan",...e),be=(...e)=>g("gray",...e);var Ce=(e,r)=>({kind:"table",headers:y(e),rows:r.map(n=>y(n))});var Te=(e,...r)=>({kind:"alert",level:e,children:y(r)}),h=e=>{switch(e.kind){case"text":return e.value.length;case"newline":return 1;case"bold":case"dim":case"italic":case"underline":case"strikethrough":case"color":case"group":return e.children.reduce((r,n)=>r+h(n),0);case"code-block":return e.value.length;case"table":case"list":return 0;case"gauge":{let r=e.width??20,n=e.label?` ${e.label}`:"";return r+` ${e.percent}%`.length+n.length}case"separator":return 0;case"alert":return 2+e.children.reduce((r,n)=>r+h(n),0)}};var k=(e,r)=>{let n=typeof e=="string"?"text":e instanceof Uint8Array?"bytes":"structured";return{data:e,meta:{timestamp:Date.now(),kind:n,channel:"stdout",...r}}};var E=e=>{switch(e.kind){case"text":return e.value;case"newline":return`
2
+ `;case"bold":case"dim":case"italic":case"underline":case"strikethrough":case"color":case"group":return e.children.map(E).join("");case"code-block":return e.value.split(`
3
+ `).map(r=>` ${r}`).join(`
4
+ `)+`
5
+ `;case"table":{let r=e.headers.map((s,u)=>{let i=e.rows.reduce(($,c)=>{let m=c[u];return Math.max($,m!==void 0?h(m):0)},0);return Math.max(h(s),i)}),n=(s,u)=>{let i=E(s),$=h(s);return i+" ".repeat(Math.max(0,u-$))},o=e.headers.map((s,u)=>n(s,r[u])).join(" "),t=r.map(s=>"-".repeat(s)).join(" "),l=e.rows.map(s=>s.map((u,i)=>n(u,r[i])).join(" ")).join(`
6
+ `);return`${o}
7
+ ${t}
8
+ ${l}
9
+ `}case"list":return e.items.map(r=>` - ${r.map(E).join("")}`).join(`
10
+ `)+`
11
+ `;case"gauge":{let r=e.width??20,n=Math.round(r*e.percent/100),o=r-n,t=`[${"=".repeat(n)}${" ".repeat(o)}]`,l=e.label?` ${e.label}`:"";return`${t} ${e.percent}%${l}`}case"separator":return e.label?`--- ${e.label} ---
12
+ `:`${"\u2500".repeat(40)}
13
+ `;case"alert":return`[${{info:"INFO",success:"OK",warning:"WARN",error:"ERROR"}[e.level]}] ${e.children.map(E).join("")}`}},W=()=>({name:"plain",render:e=>e.map(E).join("")});var v=()=>{let e=[];return{name:"buffer",writable:new WritableStream({write(r){e.push(r)}}),chunks:()=>e,items:()=>e.map(r=>r.data),clear:()=>{e.length=0}}};var se=e=>{console.error(`[streams] Error at chunk #${e.chunkIndex} (${e.pendingCount} pending):`,e.error)},z=e=>{let r=[],n=e?.onError??se,o=e?.renderer??W(),t=!1,l=0,s=!1,u=[],c=(()=>{let p=e?.sink??v(),S=e?.layers??[];if(S.length===0)return p.writable;let{readable:w,writable:te}=new TransformStream,A=w;for(let B of S)A=A.pipeThrough(B.transform());return A.pipeTo(p.writable).catch(B=>{n({error:B,chunkIndex:l,pendingCount:r.length,lastChunk:r[r.length-1]})}),te})().getWriter(),m=async()=>{try{for(;r.length>0;){let p=r.shift();try{await c.ready,await c.write(p),l++}catch(S){let w=r.length;r.length=0,n({error:S,chunkIndex:l,pendingCount:w,lastChunk:p});break}}}finally{t=!1;for(let p of u.splice(0))p()}},x=()=>{t||(t=!0,queueMicrotask(m))},L=p=>{s||(r.push(p),x())},j={write:(...p)=>{let S=y(p),w=o.render(S);L(k(w))},writeln:(...p)=>{let S=y(p),w=o.render(S)+`
14
+ `;L(k(w))},flush:()=>t?new Promise(p=>{u.push(p)}):Promise.resolve(),close:async()=>{s=!0,await j.flush();try{await c.close()}catch{}},pipe:(...p)=>z({sink:e?.sink,renderer:e?.renderer,layers:[...e?.layers??[],...p],onError:n})};return j};var P=class extends Error{constructor(r){super(r),this.name="StreamError"}},b=class extends P{cause;constructor(r,n){super(r),this.name="PipelineError",this.cause=n}},C=class extends P{constructor(r){super(`Pipeline timed out after ${r}ms`),this.name="TimeoutError"}};var pe=()=>{let e,r=[],n,o={from:t=>(e=t,o),through:(...t)=>(r.push(...t),o),to:t=>(n=t,o),run:async t=>{if(e===void 0)throw new b("Pipeline has no source. Call .from() first.");if(n===void 0)throw new b("Pipeline has no sink. Call .to() first.");let l=e.readable;for(let i of r)l=l.pipeThrough(i.transform());let s=new AbortController,u;t?.timeout!==void 0&&t.timeout>0&&(u=setTimeout(()=>{s.abort(new C(t.timeout))},t.timeout));try{await l.pipeTo(n.writable,{signal:s.signal})}catch(i){throw i instanceof C?i:i instanceof DOMException&&i.name==="AbortError"?new C(t?.timeout??0):new b(`Pipeline failed: ${i instanceof Error?i.message:String(i)}`,i instanceof Error?i:void 0)}finally{u!==void 0&&clearTimeout(u)}},collect:async()=>{let t=v();return n=t,await o.run(),t.items()}};return o};var Z={};H(Z,{buffer:()=>v,multiplex:()=>V,nullSink:()=>J,stderr:()=>Y,stdout:()=>X,writable:()=>Q});var q,le=()=>(q===void 0&&(q=new TextEncoder),q),F=new WeakMap,M=(e,r)=>{let n=le().encode(r),t=(F.get(e)??Promise.resolve()).then(async()=>{let l=e.getWriter();try{await l.write(n)}finally{l.releaseLock()}});return F.set(e,t.catch(()=>{})),t};var X=()=>{let e=I.process.stdout;return{name:"stdout",writable:new WritableStream({async write(r){await M(e,String(r.data))}})}};var Y=()=>{let e=I.process.stderr;return{name:"stderr",writable:new WritableStream({async write(r){await M(e,String(r.data))}})}};var J=()=>({name:"null",writable:new WritableStream({write(e){}})});var Q=(e,r)=>({name:r??"writable",writable:e});var V=(...e)=>{let r=e.map(n=>({name:n.name,writer:n.writable.getWriter()}));return{name:`multiplex(${e.map(n=>n.name).join(",")})`,writable:new WritableStream({async write(n){await Promise.all(r.map(o=>o.writer.write(n)))},async close(){await Promise.all(r.map(n=>n.writer.close()))},async abort(n){await Promise.all(r.map(o=>o.writer.abort(n)))}})}};var ne={};H(ne,{ansi:()=>ee,markdown:()=>re,plain:()=>W});var a="\x1B[",ue=`${a}0m`,d={bold:[`${a}1m`,`${a}22m`],dim:[`${a}2m`,`${a}22m`],italic:[`${a}3m`,`${a}23m`],underline:[`${a}4m`,`${a}24m`],strikethrough:[`${a}9m`,`${a}29m`]},D={black:`${a}30m`,red:`${a}31m`,green:`${a}32m`,yellow:`${a}33m`,blue:`${a}34m`,magenta:`${a}35m`,cyan:`${a}36m`,white:`${a}37m`,gray:`${a}90m`},G=`${a}39m`,T=e=>{switch(e.kind){case"text":return e.value;case"newline":return`
15
+ `;case"bold":case"dim":case"italic":case"underline":case"strikethrough":{let[r,n]=d[e.kind];return`${r}${e.children.map(T).join("")}${n}`}case"color":return`${D[e.color]??D.white}${e.children.map(T).join("")}${G}`;case"group":return e.children.map(T).join("");case"code-block":{let r=d.dim[0],n=d.dim[1];return e.value.split(`
16
+ `).map(o=>`${r} ${o}${n}`).join(`
17
+ `)+`
18
+ `}case"table":{let r=e.headers.map((c,m)=>{let x=e.rows.reduce((L,j)=>{let p=j[m];return Math.max(L,p!==void 0?h(p):0)},0);return Math.max(h(c),x)}),n=d.bold[0],o=d.bold[1],t=d.dim[0],l=d.dim[1],s=(c,m)=>{let x=T(c),L=h(c);return x+" ".repeat(Math.max(0,m-L))},u=e.headers.map((c,m)=>`${n}${s(c,r[m])}${o}`).join(" "),i=`${t}${r.map(c=>"\u2500".repeat(c)).join("\u2500\u2500")}${l}`,$=e.rows.map(c=>c.map((m,x)=>s(m,r[x])).join(" ")).join(`
19
+ `);return`${u}
20
+ ${i}
21
+ ${$}
22
+ `}case"list":return e.items.map(r=>` \u2022 ${r.map(T).join("")}`).join(`
23
+ `)+`
24
+ `;case"gauge":{let r=e.width??20,n=Math.round(r*e.percent/100),o=r-n,t=`${D.green}${"\u2588".repeat(n)}${G}${d.dim[0]}${"\u2591".repeat(o)}${d.dim[1]}`,l=` ${e.percent}%`,s=e.label?`${d.dim[0]} ${e.label}${d.dim[1]}`:"";return`${t}${l}${s}`}case"separator":{let r=d.dim[0],n=d.dim[1];if(e.label){let o="\u2500".repeat(Math.max(0,33-e.label.length));return`${r}\u2500\u2500\u2500\u2500 ${e.label} ${o}${n}
25
+ `}return`${r}${"\u2500".repeat(40)}${n}
26
+ `}case"alert":{let r={info:"\u2139",success:"\u2713",warning:"\u25B2",error:"\u2717"},n={info:"cyan",success:"green",warning:"yellow",error:"red"},o=r[e.level];return`${D[n[e.level]]}${o}${G} ${e.children.map(T).join("")}`}}},ee=()=>({name:"ansi",render:e=>{let r=e.map(T).join("");return r.includes(a)?r+ue:r}});var f=e=>{switch(e.kind){case"text":return e.value;case"newline":return`
27
+ `;case"bold":return`**${e.children.map(f).join("")}**`;case"italic":return`*${e.children.map(f).join("")}*`;case"strikethrough":return`~~${e.children.map(f).join("")}~~`;case"dim":case"underline":case"color":case"group":return e.children.map(f).join("");case"code-block":return`\`\`\`${e.language??""}
28
+ ${e.value}
29
+ \`\`\`
30
+ `;case"table":{let r=`| ${e.headers.map(f).join(" | ")} |`,n=`| ${e.headers.map(()=>"---").join(" | ")} |`,o=e.rows.map(t=>`| ${t.map(f).join(" | ")} |`).join(`
31
+ `);return`${r}
32
+ ${n}
33
+ ${o}
34
+ `}case"list":return e.items.map(r=>`- ${r.map(f).join("")}`).join(`
35
+ `)+`
36
+ `;case"gauge":{let r=e.label?` \u2014 ${e.label}`:"";return`**${e.percent}%**${r}`}case"separator":return e.label?`--- ${e.label} ---
37
+ `:`---
38
+ `;case"alert":{let r={info:"\u2139 Info",success:"\u2713 Success",warning:"\u26A0 Warning",error:"\u2717 Error"},n=e.children.map(f).join("");return`> **${r[e.level]}:** ${n}
39
+ `}}},re=()=>({name:"markdown",render:e=>e.map(f).join("")});export{k as a,oe as b,me as c,ye as d,he as e,fe as f,Se as g,ke as h,xe as i,we as j,ge as k,be as l,Ce as m,Te as n,z as o,pe as p,Z as q,ne as r};