@andares/pi-toolkits 0.12.4 → 0.14.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 (77) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +134 -17
  3. package/README.zh-CN.md +115 -16
  4. package/package.json +24 -11
  5. package/src/features/ask/index.ts +6 -0
  6. package/src/features/init/apply.ts +32 -12
  7. package/src/features/init/audit-uat.test.ts +103 -0
  8. package/src/features/init/audit.ts +148 -0
  9. package/src/features/init/detect.ts +4 -0
  10. package/src/features/init/index.ts +47 -2
  11. package/src/features/init/plan.ts +11 -0
  12. package/src/features/init/refresh.test.ts +208 -0
  13. package/src/features/init/refresh.ts +255 -0
  14. package/src/features/init/spec.ts +20 -0
  15. package/src/features/init/templates/agents-skeleton.md +2 -0
  16. package/src/features/init/templates/uat-readme.md +53 -0
  17. package/src/features/init/templates/workflow-block.md +21 -0
  18. package/src/features/init/templates.test.ts +3 -1
  19. package/src/features/init/templates.ts +2 -0
  20. package/src/features/init/types.ts +12 -1
  21. package/src/features/permission/index.ts +32 -0
  22. package/src/features/permission/policy.test.ts +10 -0
  23. package/src/features/permission/units.test.ts +157 -0
  24. package/src/features/permission/units.ts +317 -15
  25. package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
  26. package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
  27. package/src/features/plan/assets/index.html +14 -0
  28. package/src/features/plan/assets.test.ts +64 -0
  29. package/src/features/plan/blocks.test.ts +77 -0
  30. package/src/features/plan/blocks.ts +153 -0
  31. package/src/features/plan/diff.test.ts +144 -0
  32. package/src/features/plan/diff.ts +193 -0
  33. package/src/features/plan/feedback.test.ts +233 -0
  34. package/src/features/plan/feedback.ts +182 -0
  35. package/src/features/plan/index.test.ts +385 -0
  36. package/src/features/plan/index.ts +433 -0
  37. package/src/features/plan/prompt.test.ts +91 -0
  38. package/src/features/plan/prompt.ts +110 -0
  39. package/src/features/plan/render.test.ts +94 -0
  40. package/src/features/plan/render.ts +131 -0
  41. package/src/features/plan/server.test.ts +374 -0
  42. package/src/features/plan/server.ts +272 -0
  43. package/src/features/plan/store.test.ts +145 -0
  44. package/src/features/plan/store.ts +244 -0
  45. package/src/features/review/index.ts +54 -28
  46. package/src/features/review/review.test.ts +46 -1
  47. package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
  48. package/src/features/uat/assets/index-DCBQCsli.js +1 -0
  49. package/src/features/uat/assets/index.html +14 -0
  50. package/src/features/uat/constants.ts +23 -0
  51. package/src/features/uat/index.test.ts +404 -0
  52. package/src/features/uat/index.ts +329 -0
  53. package/src/features/uat/item-tool.ts +280 -0
  54. package/src/features/uat/ledger.test.ts +249 -0
  55. package/src/features/uat/ledger.ts +504 -0
  56. package/src/features/uat/prompt.ts +78 -0
  57. package/src/features/uat/record-tool.ts +167 -0
  58. package/src/features/uat/records.test.ts +145 -0
  59. package/src/features/uat/records.ts +268 -0
  60. package/src/features/uat/server.ts +181 -0
  61. package/src/features/uat/state.test.ts +41 -0
  62. package/src/features/uat/state.ts +67 -0
  63. package/src/features/whats-new/changelog.ts +104 -0
  64. package/src/features/whats-new/constants.ts +35 -0
  65. package/src/features/whats-new/index.ts +146 -0
  66. package/src/features/whats-new/notice.ts +68 -0
  67. package/src/features/whats-new/paths.ts +29 -0
  68. package/src/features/whats-new/store.ts +114 -0
  69. package/src/features/whats-new/version.ts +43 -0
  70. package/src/features/whats-new/whats-new.test.ts +460 -0
  71. package/src/index.ts +13 -1
  72. package/src/lib/ask-control.ts +25 -0
  73. package/src/lib/opener.test.ts +72 -0
  74. package/src/lib/opener.ts +121 -0
  75. package/src/lib/permission-control.ts +39 -0
  76. package/src/lib/startup.test.ts +1 -1
  77. package/src/lib/web-review.ts +341 -0
@@ -0,0 +1 @@
1
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return t(this.context.count)},getNextContextId(){return t(this.context.count++)}};function t(t){let n=String(t),r=n.length-1;return e.context.id+(r?String.fromCharCode(96+r):``)+n}function n(t){e.context=t}var r=(e,t)=>e===t,i=Symbol(`solid-track`),a={equals:r},o=null,s=I,c=1,l=2,u={owned:null,cleanups:null,context:null,owner:null},d=null,f=null,p=null,m=null,h=null,g=0;function _(e,t){let n=p,r=d,i=e.length===0,a=t===void 0?r:t,o=i?u:{owned:null,cleanups:null,context:a?a.context:null,owner:a},s=i?e:()=>e(v(o));d=o,p=null;try{return F(s,!0)}finally{p=n,d=r}}function v(e){return()=>C(()=>B(e))}function y(e,t){t=t?Object.assign({},a,t):a;let n={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0};return[A.bind(n),e=>(typeof e==`function`&&(e=f&&f.running&&f.sources.has(n)?e(n.tValue):e(n.value)),ee(n,e))]}function b(e,t,n){j(N(e,t,!1,c))}function x(e,t,n){s=L;let r=N(e,t,!1,c),i=k&&O(k);i&&(r.suspense=i),(!n||!n.render)&&(r.user=!0),h?h.push(r):j(r)}function S(e,t,n){n=n?Object.assign({},a,n):a;let r=N(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,j(r),A.bind(r)}function C(e){if(p===null)return e();let t=p;p=null;try{return e()}finally{p=t}}function w(e){x(()=>C(e))}function T(e){return d===null||(d.cleanups===null?d.cleanups=[e]:d.cleanups.push(e)),e}var[E,D]=y(!1);function O(e){let t;return d&&d.context&&(t=d.context[e.id])!==void 0?t:e.defaultValue}var k;function A(){let e=f&&f.running;if(this.sources&&(e?this.tState:this.state)){if((e?this.tState:this.state)===c)j(this);else{let e=m;m=null,F(()=>R(this),!1),m=e}}if(p){let e=this.observers;if(!e||e[e.length-1]!==p){let t=e?e.length:0;p.sources?(p.sources.push(this),p.sourceSlots.push(t)):(p.sources=[this],p.sourceSlots=[t]),e?(e.push(p),this.observerSlots.push(p.sources.length-1)):(this.observers=[p],this.observerSlots=[p.sources.length-1])}}return e&&f.sources.has(this)?this.tValue:this.value}function ee(e,t,n){let r=f&&f.running&&f.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(r,t)){if(f){let r=f.running;(r||!n&&f.sources.has(e))&&(f.sources.add(e),e.tValue=t),r||(e.value=t)}else e.value=t;e.observers&&e.observers.length&&F(()=>{for(let t=0;t<e.observers.length;t+=1){let n=e.observers[t],r=f&&f.running;r&&f.disposed.has(n)||((r?!n.tState:!n.state)&&(n.pure?m.push(n):h.push(n),n.observers&&z(n)),r?n.tState=c:n.state=c)}if(m.length>1e6)throw m=[],Error()},!1)}return t}function j(e){if(!e.fn)return;B(e);let t=g;M(e,f&&f.running&&f.sources.has(e)?e.tValue:e.value,t),f&&!f.running&&f.sources.has(e)&&queueMicrotask(()=>{F(()=>{f&&(f.running=!0),p=d=e,M(e,e.tValue,t),p=d=null},!1)})}function M(e,t,n){let r,i=d,a=p;p=d=e;try{r=e.fn(t)}catch(t){return e.pure&&(f&&f.running?(e.tState=c,e.tOwned&&e.tOwned.forEach(B),e.tOwned=void 0):(e.state=c,e.owned&&e.owned.forEach(B),e.owned=null)),e.updatedAt=n+1,U(t)}finally{p=a,d=i}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&`observers`in e?ee(e,r,!0):f&&f.running&&e.pure?(f.sources.has(e)||(e.value=r),f.sources.add(e),e.tValue=r):e.value=r,e.updatedAt=n)}function N(e,t,n,r=c,i){let a={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:d,context:d?d.context:null,pure:n};return f&&f.running&&(a.state=0,a.tState=r),d===null||d!==u&&(f&&f.running&&d.pure?d.tOwned?d.tOwned.push(a):d.tOwned=[a]:d.owned?d.owned.push(a):d.owned=[a]),a}function P(e){let t=f&&f.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===l)return R(e);if(e.suspense&&C(e.suspense.inFallback))return e.suspense.effects.push(e);let n=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<g);){if(t&&f.disposed.has(e))return;(t?e.tState:e.state)&&n.push(e)}for(let r=n.length-1;r>=0;r--){if(e=n[r],t){let t=e,i=n[r+1];for(;(t=t.owner)&&t!==i;)if(f.disposed.has(t))return}if((t?e.tState:e.state)===c)j(e);else if((t?e.tState:e.state)===l){let t=m;m=null,F(()=>R(e,n[0]),!1),m=t}}}function F(e,t){if(m)return e();let n=!1;t||(m=[]),h?n=!0:h=[],g++;try{let t=e();return te(n),t}catch(e){n||(h=null),m=null,U(e)}}function te(e){if(m&&=(I(m),null),e)return;let t;if(f){if(!f.promises.size&&!f.queue.size){let e=f.sources,n=f.disposed;h.push.apply(h,f.effects),t=f.resolve;for(let e of h)`tState`in e&&(e.state=e.tState),delete e.tState;f=null,F(()=>{for(let e of n)B(e);for(let t of e){if(t.value=t.tValue,t.owned)for(let e=0,n=t.owned.length;e<n;e++)B(t.owned[e]);t.tOwned&&(t.owned=t.tOwned),delete t.tValue,delete t.tOwned,t.tState=0}D(!1)},!1)}else if(f.running){f.running=!1,f.effects.push.apply(f.effects,h),h=null,D(!0);return}}let n=h;h=null,n.length&&F(()=>s(n),!1),t&&t()}function I(e){for(let t=0;t<e.length;t++)P(e[t])}function L(t){let r,i=0;for(r=0;r<t.length;r++){let e=t[r];e.user?t[i++]=e:P(e)}if(e.context){if(e.count){e.effects||=[],e.effects.push(...t.slice(0,i));return}n()}for(e.effects&&(e.done||!e.count)&&(t=[...e.effects,...t],i+=e.effects.length,delete e.effects),r=0;r<i;r++)P(t[r])}function R(e,t){let n=f&&f.running;n?e.tState=0:e.state=0;for(let r=0;r<e.sources.length;r+=1){let i=e.sources[r];if(i.sources){let e=n?i.tState:i.state;e===c?i!==t&&(!i.updatedAt||i.updatedAt<g)&&P(i):e===l&&R(i,t)}}}function z(e){let t=f&&f.running;for(let n=0;n<e.observers.length;n+=1){let r=e.observers[n];(t?!r.tState:!r.state)&&(t?r.tState=l:r.state=l,r.pure?m.push(r):h.push(r),r.observers&&z(r))}}function B(e){let t;if(e.sources)for(;e.sources.length;){let t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){let e=r.pop(),i=t.observerSlots.pop();n<r.length&&(e.sourceSlots[i]=n,r[n]=e,t.observerSlots[n]=i)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)B(e.tOwned[t]);delete e.tOwned}if(f&&f.running&&e.pure)V(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)B(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}f&&f.running?e.tState=0:e.state=0}function V(e,t){if(t||(e.tState=0,f.disposed.add(e)),e.owned)for(let t=0;t<e.owned.length;t++)V(e.owned[t])}function ne(e){return e instanceof Error?e:Error(typeof e==`string`?e:`Unknown error`,{cause:e})}function H(e,t,n){try{for(let n of t)n(e)}catch(e){U(e,n&&n.owner||null)}}function U(e,t=d){let n=o&&t&&t.context&&t.context[o],r=ne(e);if(!n)throw r;h?h.push({fn(){H(r,n,t)},state:c}):H(r,n,t)}var W=Symbol(`fallback`);function G(e){for(let t=0;t<e.length;t++)e[t]()}function re(e,t,n={}){let r=[],a=[],o=[],s=0,c=t.length>1?[]:null;return T(()=>G(o)),()=>{let l=e()||[],u=l.length,d,f;return l[i],C(()=>{let e,t,i,m,h,g,v,y,b;if(u===0)s!==0&&(G(o),o=[],r=[],a=[],s=0,c&&=[]),n.fallback&&(r=[W],a[0]=_(e=>(o[0]=e,n.fallback())),s=1);else if(s===0){for(a=Array(u),f=0;f<u;f++)r[f]=l[f],a[f]=_(p);s=u}else{for(i=Array(u),m=Array(u),c&&(h=Array(u)),g=0,v=Math.min(s,u);g<v&&r[g]===l[g];g++);for(v=s-1,y=u-1;v>=g&&y>=g&&r[v]===l[y];v--,y--)i[y]=a[v],m[y]=o[v],c&&(h[y]=c[v]);for(e=new Map,t=Array(y+1),f=y;f>=g;f--)b=l[f],d=e.get(b),t[f]=d===void 0?-1:d,e.set(b,f);for(d=g;d<=v;d++)b=r[d],f=e.get(b),f!==void 0&&f!==-1?(i[f]=a[d],m[f]=o[d],c&&(h[f]=c[d]),f=t[f],e.set(b,f)):o[d]();for(f=g;f<u;f++)f in i?(a[f]=i[f],o[f]=m[f],c&&(c[f]=h[f],c[f](f))):a[f]=_(p);a=a.slice(0,s=u),r=l.slice(0)}return a});function p(e){if(o[f]=e,c){let[e,n]=y(f);return c[f]=n,t(l[f],e)}return t(l[f])}}}function K(e,t){return C(()=>e(t||{}))}var ie=e=>`Stale read from <${e}>.`;function q(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return S(re(()=>e.each,e.children,t||void 0))}function J(e){let t=e.keyed,n=S(()=>e.when,void 0,void 0),r=t?n:S(n,void 0,{equals:(e,t)=>!e==!t});return S(()=>{let i=r();if(i){let a=e.children;return typeof a==`function`&&a.length>0?C(()=>a(t?i:()=>{if(!C(r))throw ie(`Show`);return n()})):a}return e.fallback},void 0,void 0)}var Y=e=>S(()=>e());function ae(e,t,n){let r=n.length,i=t.length,a=r,o=0,s=0,c=t[i-1].nextSibling,l=null;for(;o<i||s<a;){if(t[o]===n[s]){o++,s++;continue}for(;t[i-1]===n[a-1];)i--,a--;if(i===o){let t=a<r?s?n[s-1].nextSibling:n[a-s]:c;for(;s<a;)e.insertBefore(n[s++],t)}else if(a===s)for(;o<i;)(!l||!l.has(t[o]))&&t[o].remove(),o++;else if(t[o]===n[a-1]&&n[s]===t[i-1]){let r=t[--i].nextSibling;e.insertBefore(n[s++],t[o++].nextSibling),e.insertBefore(n[--a],r),t[i]=n[a]}else{if(!l){l=new Map;let e=s;for(;e<a;)l.set(n[e],e++)}let r=l.get(t[o]);if(r!=null){if(s<r&&r<a){let c=o,u=1,d;for(;++c<i&&c<a&&(d=l.get(t[c]))!=null&&d===r+u;)u++;if(u>r-s){let i=t[o];for(;s<r;)e.insertBefore(n[s++],i)}else e.replaceChild(n[s++],t[o++])}else o++}else t[o++].remove()}}}var oe=`_$DX_DELEGATE`;function se(e,t,n,r={}){let i;return _(r=>{i=r,t===document?e():Z(t,e(),!n&&t.firstChild?null:void 0,n)},r.owner),()=>{i(),t.textContent=``}}function X(e,t,n,r){let i,a=()=>{let t=r?document.createElementNS(`http://www.w3.org/1998/Math/MathML`,`template`):document.createElement(`template`);return t.innerHTML=e,n?t.content.firstChild.firstChild:r?t.firstChild:t.content.firstChild},o=t?()=>C(()=>document.importNode(i||=a(),!0)):()=>(i||=a()).cloneNode(!0);return o.cloneNode=o,o}function ce(e,t=window.document){let n=t[oe]||(t[oe]=new Set);for(let r=0,i=e.length;r<i;r++){let i=e[r];n.has(i)||(n.add(i),t.addEventListener(i,he))}}function le(e,t,n){pe(e)||(n==null?e.removeAttribute(t):e.setAttribute(t,n))}function ue(e,t){pe(e)||(t==null?e.removeAttribute(`class`):e.className=t)}function de(e,t,n,r){if(r)Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n;else if(Array.isArray(n)){let r=n[0];e.addEventListener(t,n[0]=t=>r.call(e,n[1],t))}else e.addEventListener(t,n,typeof n!=`function`&&n)}function fe(e,t,n={}){let r=Object.keys(t||{}),i=Object.keys(n),a,o;for(a=0,o=i.length;a<o;a++){let r=i[a];!r||r===`undefined`||t[r]||(me(e,r,!1),delete n[r])}for(a=0,o=r.length;a<o;a++){let i=r[a],o=!!t[i];!i||i===`undefined`||n[i]===o||!o||(me(e,i,!0),n[i]=o)}return n}function Z(e,t,n,r){if(n!==void 0&&!r&&(r=[]),typeof t!=`function`)return Q(e,t,r,n);b(r=>Q(e,t(),r,n),r)}function pe(t){return!!e.context&&!e.done&&(!t||t.isConnected)}function me(e,t,n){let r=t.trim().split(/\s+/);for(let t=0,i=r.length;t<i;t++)e.classList.toggle(r[t],n)}function he(t){if(e.registry&&e.events&&e.events.find(([e,n])=>n===t))return;let n=t.target,r=`$$${t.type}`,i=t.target,a=t.currentTarget,o=e=>Object.defineProperty(t,"target",{configurable:!0,value:e}),s=()=>{let e=n[r];if(e&&!n.disabled){let i=n[`${r}Data`];if(i===void 0?e.call(n,t):e.call(n,i,t),t.cancelBubble)return}return n.host&&typeof n.host!=`string`&&!n.host._$host&&n.contains(t.target)&&o(n.host),!0},c=()=>{for(;s()&&(n=n._$host||n.parentNode||n.host););};Object.defineProperty(t,"currentTarget",{configurable:!0,get(){return n||document}}),e.registry&&!e.done&&(e.done=_$HY.done=!0);try{if(t.composedPath){let e=t.composedPath();o(e[0]);for(let t=0;t<e.length-2&&(n=e[t],s());t++){if(n._$host){n=n._$host,c();break}if(n.parentNode===a)break}}else c();o(i)}finally{t=n=null}}function Q(e,t,n,r,i){let a=pe(e);if(a){!n&&(n=[...e.childNodes]);let t=[];for(let e=0;e<n.length;e++){let r=n[e];r.nodeType===8&&r.data.slice(0,2)===`!$`?r.remove():t.push(r)}n=t}for(;typeof n==`function`;)n=n();if(t===n)return n;let o=typeof t,s=r!==void 0;if(e=s&&n[0]&&n[0].parentNode||e,o===`string`||o===`number`){if(a||o===`number`&&(t=t.toString(),t===n))return n;if(s){let i=n[0];i&&i.nodeType===3?i.data!==t&&(i.data=t):i=document.createTextNode(t),n=$(e,n,r,i)}else n=n!==``&&typeof n==`string`?e.firstChild.data=t:e.textContent=t}else if(t==null||o===`boolean`){if(a)return n;n=$(e,n,r)}else if(o===`function`)return b(()=>{let i=t();for(;typeof i==`function`;)i=i();n=Q(e,i,n,r)}),()=>n;else if(Array.isArray(t)){let o=[],c=n&&Array.isArray(n);if(ge(o,t,n,i))return b(()=>n=Q(e,o,n,r,!0)),()=>n;if(a){if(!o.length)return n;if(r===void 0)return n=[...e.childNodes];let t=o[0];if(t.parentNode!==e)return n;let i=[t];for(;(t=t.nextSibling)!==r;)i.push(t);return n=i}if(o.length===0){if(n=$(e,n,r),s)return n}else c?n.length===0?_e(e,o,r):ae(e,n,o):(n&&$(e),_e(e,o));n=o}else if(t.nodeType){if(a&&t.parentNode)return n=s?[t]:t;if(Array.isArray(n)){if(s)return n=$(e,n,r,t);$(e,n,null,t)}else n==null||n===``||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);n=t}return n}function ge(e,t,n,r){let i=!1;for(let a=0,o=t.length;a<o;a++){let o=t[a],s=n&&n[e.length],c;if(o!=null&&o!==!0&&o!==!1){if((c=typeof o)==`object`&&o.nodeType)e.push(o);else if(Array.isArray(o))i=ge(e,o,s)||i;else if(c===`function`){if(r){for(;typeof o==`function`;)o=o();i=ge(e,Array.isArray(o)?o:[o],Array.isArray(s)?s:[s])||i}else e.push(o),i=!0}else{let t=String(o);s&&s.nodeType===3&&s.data===t?e.push(s):e.push(document.createTextNode(t))}}}return i}function _e(e,t,n=null){for(let r=0,i=t.length;r<i;r++)e.insertBefore(t[r],n)}function $(e,t,n,r){if(n===void 0)return e.textContent=``;let i=r||document.createTextNode(``);if(t.length){let r=!1;for(let a=t.length-1;a>=0;a--){let o=t[a];if(i!==o){let t=o.parentNode===e;!r&&!a?t?e.replaceChild(i,o):e.insertBefore(i,n):t&&o.remove()}else r=!0}}else e.insertBefore(i,n);return[i]}var ve=new URLSearchParams(window.location.search).get(`t`)??``;async function ye(e,t={}){let n=await fetch(e,{...t,headers:{...t.body?{"content-type":`application/json`}:{},"x-plan-token":ve,...t.headers??{}}});if(!n.ok)throw Error(`${t.method??`GET`} ${e} → HTTP ${n.status}`);return await n.json()}function be(e){return ye(e===void 0?`/api/state`:`/api/state?version=${e}`)}function xe(e,t){return ye(`/api/annotate`,{method:`POST`,body:JSON.stringify({version:e,annotations:t})})}function Se(e,t){return ye(`/api/decide`,{method:`POST`,body:JSON.stringify({action:e,version:t})})}function Ce(e){try{return JSON.parse(e.data)}catch{return}}function we(e){let t=new EventSource(`/api/events?t=${encodeURIComponent(ve)}`);return t.addEventListener(`revision`,t=>{let n=Ce(t);n&&e.onRevision(n.version)}),t.addEventListener(`annotations`,()=>e.onAnnotations()),t.addEventListener(`decided`,t=>{let n=Ce(t);n&&e.onDecided(n)}),()=>t.close()}var Te=`plan:lang`;function Ee(){let e=localStorage.getItem(Te);return e===`en`||e===`zh`?e:navigator.language.toLowerCase().startsWith(`zh`)?`zh`:`en`}function De(e){localStorage.setItem(Te,e)}var Oe={en:{title:`Plan review`,version:`v{version} of {total}`,changed:`{count} changed`,noChange:`no changes`,expanded:`collapsed unchanged`,showAll:`show unchanged`,onlyChanged:`only changed`,approve:`Approve`,deny:`Send feedback`,globalNotes:`Global notes`,notePlaceholder:`What should change here?`,addNote:`Add note`,save:`Save`,cancel:`Cancel`,remove:`Remove`,verdictChange:`must change`,verdictSuggest:`suggest`,verdictQuestion:`question`,history:`History`,back:`Back to latest`,viewingOld:`Read-only: you are viewing v{v}`,readOnly:`Read-only`,approved:`Approved`,denied:`Feedback sent`,closing:`Closing this tab…`,closeHint:`You can close this tab now.`,waiting:`Waiting for the agent…`,status_unchanged:`unchanged`,status_moved:`moved`,status_modified:`modified`,status_added:`new`,status_removed:`removed`,unchangedHidden:`{count} unchanged blocks hidden`,error:`Something went wrong: {message}`,emptyPlan:`This plan is empty.`,notesHint:`Notes are sent with either decision — approve just means “start implementing”.`,noteCount:`{count} notes`},zh:{title:`计划评审`,version:`第 {version} / {total} 版`,changed:`{count} 处改动`,noChange:`无改动`,expanded:`已折叠未变块`,showAll:`显示未变块`,onlyChanged:`只看改动`,approve:`批准`,deny:`提交意见`,globalNotes:`全局批注`,notePlaceholder:`这里应该怎么改?`,addNote:`添加批注`,save:`保存`,cancel:`取消`,remove:`删除`,verdictChange:`必须改`,verdictSuggest:`建议`,verdictQuestion:`疑问`,history:`历史`,back:`回到最新版`,viewingOld:`只读:正在查看第 {v} 版`,readOnly:`只读`,approved:`已批准`,denied:`意见已提交`,closing:`正在关闭标签页…`,closeHint:`现在可以关闭这个标签页了。`,waiting:`等待模型继续…`,status_unchanged:`未变`,status_moved:`位置移动`,status_modified:`已修改`,status_added:`新增`,status_removed:`已删除`,unchangedHidden:`隐藏了 {count} 个未变块`,error:`出错了:{message}`,emptyPlan:`计划是空的。`,notesHint:`批注无论批准还是提意见都会送达;批准只是让模型开始实施。`,noteCount:`{count} 条批注`}};function ke(e,t,n={}){return(Oe[e][t]??t).replace(/\{(\w+)\}/g,(e,t)=>String(n[t]??`{${t}}`))}var Ae=X(`<span class=readonly>`),je=X(`<div class=error>`),Me=X(`<div class=banner><button class=link>`),Ne=X(`<div class=done><div class=done-title></div><div class=done-hint>`),Pe=X(`<p class=empty>`),Fe=X(`<div class=hidden-note><button class=link>`),Ie=X(`<div class=global-panel>`),Le=X(`<div class=page><header class=topbar><div class=topbar-left><span class=slug></span><span class=version></span><span class=changed></span></div><div class=topbar-right><button class=ghost></button><button class=ghost> (<!>)</button><button class=lang></button></div></header><div class=history><span class=history-label></span></div><main class=blocks></main><footer class=footer><div class=hint> · </div><div class=actions><button class=deny></button><button class=approve>`),Re=X(`<span class=chip-changed>+`),ze=X(`<button class=chip>v`),Be=X(`<button class=add>+ `),Ve=X(`<article class=block><div class=block-head><span></span><span class=block-id></span></div><div class=block-body>`),He=X(`<button class=remove>`),Ue=X(`<div class=note><span class=note-verdict></span><span class=note-text>`),We=X(`<div class=note><span class=note-verdict></span><span class=note-text></span><button class=remove>`),Ge=X(`<div class=editor><div class=verdicts></div><textarea></textarea><div class=editor-actions><button class=ghost></button><button class=primary>`),Ke=X(`<label><input type=radio name=verdict>`);function qe(){let[e,t]=y(Ee()),[n,r]=y(),[i,a]=y(),[o,s]=y(),[c,l]=y(),[u,d]=y(!1),[f,p]=y(),[m,h]=y(``),[g,_]=y(`change`),[v,x]=y(!1),C=(t,n)=>ke(e(),t,n);async function E(e){try{let t=await be(e);r(t),s(void 0),l(t.decided&&t.decision?t.decision.action:void 0)}catch(e){s(e instanceof Error?e.message:String(e))}}w(()=>{E(),T(we({onRevision:()=>{i()===void 0&&E()},onAnnotations:()=>{i()===void 0&&E()},onDecided:e=>l(e.action)}))});let D=S(()=>n()?.items??[]),O=S(()=>D().filter(e=>e.status!==`unchanged`).length),k=S(()=>!u()&&O()>0),A=S(()=>k()?D().filter(e=>e.status===`unchanged`).length:0),ee=S(()=>k()?D().filter(e=>e.status!==`unchanged`):D()),j=S(()=>n()?.history[0]?.n??n()?.version),M=S(()=>{let e=n();return e!==void 0&&e.version!==j()}),N=e=>n()?.annotations.blocks.find(t=>t.blockId===e)?.annotations??[],P=S(()=>{let e=n()?.annotations;if(!e)return 0;let t=e.blocks.reduce((e,t)=>e+t.annotations.length,0);return e.global.length+t});async function F(e){let t=n();if(!t)return;let i={...t,annotations:e};r(i);try{await xe(t.version,e)}catch(e){s(e instanceof Error?e.message:String(e)),await E(t.version)}}async function te(e){let t=m().trim();if(t===``)return;let r=n();if(!r)return;let i={verdict:g(),comment:t},a;if(e===void 0)a={...r.annotations,global:[...r.annotations.global,i]};else{let t=r.annotations.blocks.slice(),n=t.findIndex(t=>t.blockId===e);n===-1?t.push({blockId:e,annotations:[i]}):t[n]={...t[n],annotations:[...t[n].annotations,i]},a={...r.annotations,blocks:t}}p(void 0),h(``),await F(a)}async function I(e,t){let r=n();if(!r)return;let i;i=e===void 0?{...r.annotations,global:r.annotations.global.filter((e,n)=>n!==t)}:{...r.annotations,blocks:r.annotations.blocks.map(n=>n.blockId===e?{...n,annotations:n.annotations.filter((e,n)=>n!==t)}:n).filter(e=>e.annotations.length>0)},await F(i)}async function L(e){let t=n();if(t)try{await Se(e,t.version),l(e),window.close(),setTimeout(()=>x(!0),300)}catch(e){s(e instanceof Error?e.message:String(e))}}let R=e=>`badge badge-${e}`;return(()=>{var r=Le(),s=r.firstChild,l=s.firstChild,y=l.firstChild,x=y.nextSibling,S=x.nextSibling,w=l.nextSibling.firstChild,T=w.nextSibling,D=T.firstChild,k=D.nextSibling;k.nextSibling;var F=T.nextSibling,z=s.nextSibling,B=z.firstChild,V=z.nextSibling,ne=V.nextSibling,H=ne.firstChild,U=H.firstChild,W=H.nextSibling.firstChild,G=W.nextSibling;return Z(y,()=>n()?.slug),Z(x,()=>C(`version`,{version:n()?.version??0,total:n()?.totalVersions??0})),Z(S,(()=>{var e=Y(()=>O()>0);return()=>e()?C(`changed`,{count:O()}):C(`noChange`)})()),Z(l,K(J,{get when(){return M()},get children(){var e=Ae();return Z(e,()=>C(`readOnly`)),e}}),null),w.$$click=()=>d(!u()),Z(w,(()=>{var e=Y(()=>!!u());return()=>e()?C(`onlyChanged`):C(`showAll`)})()),T.$$click=()=>p({blockId:void 0}),Z(T,()=>C(`globalNotes`),D),Z(T,()=>n()?.annotations.global.length??0,k),F.$$click=()=>{let n=e()===`en`?`zh`:`en`;t(n),De(n)},Z(F,()=>e()===`en`?`中文`:`EN`),Z(r,K(J,{get when(){return o()},get children(){var e=je();return Z(e,()=>C(`error`,{message:o()??``})),e}}),z),Z(r,K(J,{get when(){return M()},get children(){var e=Me(),t=e.firstChild;return Z(e,()=>C(`viewingOld`,{v:i()??0}),t),t.$$click=()=>{a(void 0),E()},Z(t,()=>C(`back`)),e}}),z),Z(r,K(J,{get when(){return c()},get children(){var e=Ne(),t=e.firstChild,n=t.nextSibling;return Z(t,(()=>{var e=Y(()=>c()===`approve`);return()=>e()?C(`approved`):C(`denied`)})()),Z(n,(()=>{var e=Y(()=>!!v());return()=>e()?C(`closeHint`):C(`closing`)})()),e}}),z),Z(B,()=>C(`history`)),Z(z,K(q,{get each(){return n()?.history??[]},children:e=>(()=>{var t=ze();return t.firstChild,t.$$click=()=>{e.n===j()?(a(void 0),E()):(a(e.n),E(e.n))},Z(t,()=>e.n,null),Z(t,K(J,{get when(){return e.changed>0},get children(){var t=Re();return t.firstChild,Z(t,()=>e.changed,null),t}}),null),b(()=>t.classList.toggle(`active`,e.n===n()?.version)),t})()}),null),Z(r,K(J,{get when(){return Y(()=>!!n())()&&n().items.length===0},get children(){var e=Pe();return Z(e,()=>C(`emptyPlan`)),e}}),V),Z(V,K(J,{get when(){return A()>0},get children(){var e=Fe(),t=e.firstChild;return Z(e,()=>C(`unchangedHidden`,{count:A()}),t),t.$$click=()=>d(!0),Z(t,()=>C(`showAll`)),e}}),null),Z(V,K(q,{get each(){return ee()},children:e=>(()=>{var t=Ve(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=n.nextSibling;return Z(r,()=>C(`status_${e.status}`)),Z(i,()=>e.id),Z(n,K(J,{get when(){return!M()},get children(){var t=Be();return t.firstChild,t.$$click=()=>{p({blockId:e.id}),h(``),_(`change`)},Z(t,()=>C(`addNote`),null),t}}),null),Z(t,K(q,{get each(){return N(e.id)},children:(t,n)=>(()=>{var r=Ue(),i=r.firstChild,a=i.nextSibling;return Z(i,()=>C(`verdict${t.verdict[0].toUpperCase()}${t.verdict.slice(1)}`)),Z(a,()=>t.comment),Z(r,K(J,{get when(){return!M()},get children(){var t=He();return t.$$click=()=>void I(e.id,n()),Z(t,()=>C(`remove`)),t}}),null),b(e=>fe(r,{[t.verdict]:!0},e)),r})()}),null),Z(t,K(J,{get when(){return Y(()=>f()?.blockId===e.id)()&&!M()},get children(){return K(Je,{draft:m,setDraft:h,verdict:g,setVerdict:_,onSave:()=>void te(e.id),onCancel:()=>p(void 0),t:C})}}),null),b(n=>{var i={[`is-`+e.status]:!0},o=R(e.status),s=e.html;return n.e=fe(t,i,n.e),o!==n.t&&ue(r,n.t=o),s!==n.a&&(a.innerHTML=n.a=s),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),Z(r,K(J,{get when(){return Y(()=>!!(f()&&f().blockId===void 0))()&&!M()},get children(){var e=Ie();return Z(e,K(q,{get each(){return n()?.annotations.global??[]},children:(e,t)=>(()=>{var n=We(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling;return Z(r,()=>e.verdict),Z(i,()=>e.comment),a.$$click=()=>void I(void 0,t()),Z(a,()=>C(`remove`)),b(t=>fe(n,{[e.verdict]:!0},t)),n})()}),null),Z(e,K(Je,{draft:m,setDraft:h,verdict:g,setVerdict:_,onSave:()=>void te(void 0),onCancel:()=>p(void 0),t:C}),null),e}}),ne),Z(H,()=>C(`notesHint`),U),Z(H,()=>C(`noteCount`,{count:P()}),null),W.$$click=()=>void L(`deny`),Z(W,()=>C(`deny`)),G.$$click=()=>void L(`approve`),Z(G,()=>C(`approve`)),b(e=>{var t=M()||c()!==void 0,n=M()||c()!==void 0;return t!==e.e&&(W.disabled=e.e=t),n!==e.t&&(G.disabled=e.t=n),e},{e:void 0,t:void 0}),r})()}function Je(e){return(()=>{var t=Ge(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling.firstChild,a=i.nextSibling;return Z(n,K(q,{each:[`change`,`suggest`,`question`],children:t=>(()=>{var n=Ke(),r=n.firstChild;return r.addEventListener(`change`,()=>e.setVerdict(t)),Z(n,()=>e.t(`verdict${t[0].toUpperCase()}${t.slice(1)}`),null),b(()=>n.classList.toggle(`active`,e.verdict()===t)),b(()=>r.checked=e.verdict()===t),n})()})),r.$$input=t=>e.setDraft(t.currentTarget.value),de(i,`click`,e.onCancel,!0),Z(i,()=>e.t(`cancel`)),de(a,`click`,e.onSave,!0),Z(a,()=>e.t(`save`)),b(t=>{var n=e.t(`notePlaceholder`),i=e.draft().trim()===``;return n!==t.e&&le(r,`placeholder`,t.e=n),i!==t.t&&(a.disabled=t.t=i),t},{e:void 0,t:void 0}),b(()=>r.value=e.draft()),t})()}ce([`click`,`input`]);var Ye=document.getElementById(`root`);Ye&&se(()=>K(qe,{}),Ye);
@@ -0,0 +1 @@
1
+ :root{--bg:#14171d;--panel:#1b1f27;--panel-2:#20252f;--line:#2b323d;--text:#d7dce4;--dim:#8b94a3;--green:#3fb950;--amber:#d29922;--blue:#58a6ff;--red:#f85149;--radius:8px;--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark}*{box-sizing:border-box}body{background:var(--bg);color:var(--text);margin:0;font:14px/1.65 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Noto Sans CJK SC,sans-serif}.page{max-width:980px;margin:0 auto;padding:0 20px 120px}.topbar{z-index:10;background:linear-gradient(var(--bg) 78%, transparent);flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;padding:14px 0 12px;display:flex;position:sticky;top:0}.topbar-left,.topbar-right{flex-wrap:wrap;align-items:center;gap:10px;display:flex}.slug{font-weight:600}.version,.changed,.readonly{color:var(--dim);font-variant-numeric:tabular-nums}.readonly{color:var(--amber);border:1px solid var(--amber);border-radius:999px;padding:0 8px}button{font:inherit;cursor:pointer;border-radius:var(--radius);border:1px solid var(--line);background:var(--panel);color:var(--text);padding:6px 12px}button:hover:not(:disabled){background:var(--panel-2);border-color:#3a4350}button:disabled{opacity:.45;cursor:not-allowed}button.primary{color:#fff;background:#1f6feb;border-color:#1f6feb}button.approve{color:#fff;background:#1a7f37;border-color:#1a7f37}button.deny{background:#3d1f22;border-color:#6e2a2f}button.link{color:var(--blue);background:0 0;border:none;padding:0 4px;text-decoration:underline}.lang{min-width:52px}.error{border:1px solid var(--red);color:#ffb4ad;border-radius:var(--radius);margin:8px 0;padding:8px 12px}.banner{border:1px solid var(--amber);border-radius:var(--radius);color:#f0d08a;margin:8px 0;padding:8px 12px}.done{border:1px solid var(--line);border-radius:var(--radius);background:var(--panel);margin:12px 0;padding:16px}.done-title{font-size:18px;font-weight:600}.done-hint{color:var(--dim)}.history{border-bottom:1px solid var(--line);flex-wrap:wrap;align-items:center;gap:8px;padding:10px 0 16px;display:flex}.history-label{color:var(--dim)}.chip{font-variant-numeric:tabular-nums;border-radius:999px;padding:2px 10px}.chip.active{border-color:var(--blue);color:var(--blue)}.chip-changed{color:var(--amber);margin-left:6px}.blocks{flex-direction:column;gap:14px;padding-top:18px;display:flex}.hidden-note{color:var(--dim);text-align:center;border:1px dashed var(--line);border-radius:var(--radius);padding:6px}.block{border:1px solid var(--line);border-left:4px solid var(--line);border-radius:var(--radius);background:var(--panel);padding:10px 14px}.block.is-added{border-left-color:var(--green)}.block.is-modified{border-left-color:var(--amber)}.block.is-moved{border-left-color:var(--blue)}.block.is-removed{border-left-color:var(--red);opacity:.75}.block.is-removed .block-body{color:var(--dim);text-decoration:line-through}.block-head{align-items:center;gap:8px;margin-bottom:6px;display:flex}.block-id{color:var(--dim);opacity:.6;font:11px/1 ui-monospace,monospace}.add{margin-left:auto;padding:2px 8px;font-size:12px}.block-body>:first-child{margin-top:0}.block-body>:last-child{margin-bottom:0}.block-body pre,.block-body code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.block-body pre{border:1px solid var(--line);border-radius:var(--radius);background:#0f1217;padding:10px 12px;overflow:auto}.block-body :not(pre)>code{background:#262c36;border-radius:4px;padding:1px 5px;font-size:.92em}.block-body a{color:var(--blue)}.block-body table{border-collapse:collapse}.block-body th,.block-body td{border:1px solid var(--line);padding:4px 8px}.block-body blockquote{border-left:3px solid var(--line);color:var(--dim);margin:0;padding-left:12px}.badge{border:1px solid var(--line);color:var(--dim);text-transform:uppercase;letter-spacing:.04em;border-radius:999px;padding:1px 8px;font-size:11px}.badge-unchanged{display:none}.badge-added{border-color:var(--green);color:var(--green)}.badge-modified{border-color:var(--amber);color:var(--amber)}.badge-moved{border-color:var(--blue);color:var(--blue)}.badge-removed{border-color:var(--red);color:var(--red)}.note{border-radius:var(--radius);background:var(--panel-2);border-left:3px solid var(--line);align-items:baseline;gap:8px;margin-top:8px;padding:6px 10px;display:flex}.note.change{border-left-color:var(--red)}.note.suggest{border-left-color:var(--blue)}.note.question{border-left-color:var(--dim)}.note-verdict{text-transform:uppercase;color:var(--dim);letter-spacing:.04em;font-size:11px}.note-text{white-space:pre-wrap;flex:1}.remove{padding:0 8px;font-size:12px}.editor,.global-panel{border:1px dashed var(--line);border-radius:var(--radius);background:var(--panel-2);margin-top:10px;padding:10px}.global-panel{margin:16px 0}.verdicts{color:var(--dim);gap:14px;margin-bottom:8px;display:flex}.verdicts label{cursor:pointer}.verdicts label.active{color:var(--text)}.verdicts input{margin-right:4px}.editor textarea{resize:vertical;width:100%;min-height:70px;color:var(--text);border:1px solid var(--line);border-radius:var(--radius);font:inherit;background:#0f1217;padding:8px}.editor-actions{justify-content:flex-end;gap:8px;margin-top:8px;display:flex}.footer{border-top:1px solid var(--line);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);background:#14171df0;justify-content:space-between;align-items:center;gap:16px;padding:12px 24px;display:flex;position:fixed;bottom:0;left:0;right:0}.hint{color:var(--dim);font-size:12px}.actions{gap:10px;display:flex}.empty{color:var(--dim)}
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="robots" content="noindex" />
7
+ <title>ask-plan</title>
8
+ <script type="module" crossorigin src="/index-C1YLIi4I.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/index-DMEpYC3V.css">
10
+ </head>
11
+ <body>
12
+ <div id="root"></div>
13
+ </body>
14
+ </html>
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Wiring between the built UI and the review server.
3
+ *
4
+ * The UI is a separate Vite app whose output is committed to
5
+ * `src/features/plan/assets/` (see `pnpm ui:check`). These assertions catch the
6
+ * failure that would otherwise only show up in a browser: the page shipping a
7
+ * bundle path the server cannot resolve (Vite's `assetsDir` and the server's
8
+ * `/assets/<file>` route have to agree).
9
+ */
10
+ import { existsSync } from "node:fs";
11
+ import { mkdtempSync, rmSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
15
+ import { startPlanServer } from "./server.js";
16
+ import { createPlanSession } from "./store.js";
17
+
18
+ const assetsDir = new URL("./assets/", import.meta.url).pathname;
19
+ const built = existsSync(join(assetsDir, "index.html"));
20
+ let agentDir: string;
21
+
22
+ beforeAll(() => {
23
+ agentDir = mkdtempSync(join(tmpdir(), "pi-plan-assets-"));
24
+ });
25
+
26
+ afterAll(() => {
27
+ rmSync(agentDir, { recursive: true, force: true });
28
+ });
29
+
30
+ describe.skipIf(!built)("built UI assets", () => {
31
+ it("serves the built page and the bundle it references", async () => {
32
+ const session = createPlanSession({ agentDir, slug: "assets", text: "## Plan\n\nbody" });
33
+ const server = await startPlanServer({
34
+ session,
35
+ portStart: 44_000 + Math.floor(Math.random() * 1000),
36
+ portAttempts: 20,
37
+ bindHost: "127.0.0.1",
38
+ urlHost: "127.0.0.1",
39
+ closeDelayMs: 0,
40
+ });
41
+ try {
42
+ const page = await fetch(`http://127.0.0.1:${server.port}/?t=${server.token}`);
43
+ expect(page.status).toBe(200);
44
+ const html = await page.text();
45
+ expect(html).toContain('<div id="root">');
46
+
47
+ const assetPath = /src="([^"]+\.js)"/.exec(html)?.[1];
48
+ expect(assetPath, "the built page must reference its bundle").toBeTruthy();
49
+ const bundle = await fetch(`http://127.0.0.1:${server.port}${assetPath}`);
50
+ expect(bundle.status).toBe(200);
51
+ expect(bundle.headers.get("content-type")).toContain("javascript");
52
+ expect((await bundle.text()).length).toBeGreaterThan(1000);
53
+
54
+ const stylePath = /href="([^"]+\.css)"/.exec(html)?.[1];
55
+ if (stylePath) {
56
+ const style = await fetch(`http://127.0.0.1:${server.port}${stylePath}`);
57
+ expect(style.status).toBe(200);
58
+ expect(style.headers.get("content-type")).toContain("text/css");
59
+ }
60
+ } finally {
61
+ await server.close();
62
+ }
63
+ });
64
+ });
@@ -0,0 +1,77 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { blockLabel, hashBlockText, normalizeBlockText, parseBlocks } from "./blocks.js";
3
+
4
+ describe("parseBlocks", () => {
5
+ it("splits paragraphs on blank lines", () => {
6
+ const blocks = parseBlocks("first para\n\nsecond para\n\nthird");
7
+ expect(blocks.map((block) => block.text)).toEqual(["first para", "second para", "third"]);
8
+ expect(blocks.map((block) => block.index)).toEqual([0, 1, 2]);
9
+ });
10
+
11
+ it("keeps a fenced code block whole even with blank lines inside", () => {
12
+ const markdown = ["intro", "", "```ts", "const a = 1;", "", "const b = 2;", "```", "", "tail"].join("\n");
13
+ const blocks = parseBlocks(markdown);
14
+ expect(blocks).toHaveLength(3);
15
+ expect(blocks[1]?.kind).toBe("code");
16
+ expect(blocks[1]?.text).toBe("```ts\nconst a = 1;\n\nconst b = 2;\n```");
17
+ });
18
+
19
+ it("closes a fence only on a run as long as the opener", () => {
20
+ const markdown = ["~~~~", "```", "still code", "```", "~~~", "still code", "~~~~"].join("\n");
21
+ const blocks = parseBlocks(markdown);
22
+ expect(blocks).toHaveLength(1);
23
+ expect(blocks[0]?.kind).toBe("code");
24
+ });
25
+
26
+ it("treats a heading line as its own block", () => {
27
+ const blocks = parseBlocks("## Title\n\ntext");
28
+ expect(blocks[0]?.kind).toBe("heading");
29
+ expect(blocks[1]?.kind).toBe("text");
30
+ });
31
+
32
+ it("classifies lists, quotes and tables", () => {
33
+ const blocks = parseBlocks("- one\n- two\n\n> quoted\n\n| a | b |\n| --- | --- |\n| 1 | 2 |");
34
+ expect(blocks.map((block) => block.kind)).toEqual(["list", "quote", "table"]);
35
+ });
36
+
37
+ it("gives duplicate paragraphs distinct ids", () => {
38
+ const blocks = parseBlocks("same\n\nsame");
39
+ expect(blocks[0]?.hash).toBe(blocks[1]?.hash);
40
+ expect(blocks[0]?.id).not.toBe(blocks[1]?.id);
41
+ expect(blocks[0]?.id.endsWith("#0")).toBe(true);
42
+ expect(blocks[1]?.id.endsWith("#1")).toBe(true);
43
+ });
44
+
45
+ it("reports 1-based start lines", () => {
46
+ const blocks = parseBlocks("a\n\nb\n\n\nc");
47
+ expect(blocks.map((block) => block.line)).toEqual([1, 3, 6]);
48
+ });
49
+
50
+ it("normalizes CRLF", () => {
51
+ const blocks = parseBlocks("a\r\n\r\nb\r\n");
52
+ expect(blocks.map((block) => block.text)).toEqual(["a", "b"]);
53
+ });
54
+
55
+ it("returns nothing for an empty or blank-only document", () => {
56
+ expect(parseBlocks("")).toEqual([]);
57
+ expect(parseBlocks("\n\n \n\n")).toEqual([]);
58
+ });
59
+ });
60
+
61
+ describe("block identity", () => {
62
+ it("ignores reflow and indentation when hashing", () => {
63
+ expect(normalizeBlockText("one two\n three")).toBe("one two three");
64
+ expect(hashBlockText("one two\n three")).toBe(hashBlockText("one two three"));
65
+ });
66
+
67
+ it("is case sensitive — a rename is a change", () => {
68
+ expect(hashBlockText("Plan")).not.toBe(hashBlockText("plan"));
69
+ });
70
+ });
71
+
72
+ describe("blockLabel", () => {
73
+ it("uses the first line and clips it", () => {
74
+ const [block] = parseBlocks("## A very long heading that keeps going and going\n\nbody");
75
+ expect(blockLabel(block!, 20)).toBe("## A very long head…");
76
+ });
77
+ });
@@ -0,0 +1,153 @@
1
+ /**
2
+ * plan blocks — the review unit of `/ask-plan`.
3
+ *
4
+ * A block is one blank-line-separated paragraph of the plan markdown: that is
5
+ * the granularity the operator annotates at ("this step is wrong"), so there is
6
+ * deliberately no AST here — no inline spans, no line-level addressing.
7
+ *
8
+ * Two rules make the model survive edits:
9
+ * - a fenced code block is ONE block, even though it usually contains blank
10
+ * lines (splitting it would turn a snippet into nonsense fragments);
11
+ * - a block's identity is a hash of its normalized text, so reflowing prose
12
+ * or re-indenting does not read as "changed", while any word change does.
13
+ *
14
+ * Duplicate paragraphs are legal in a plan (two identical steps, two identical
15
+ * bullets), so the id carries the occurrence index: `hash#0`, `hash#1`, …
16
+ */
17
+ import { createHash } from "node:crypto";
18
+
19
+ export type BlockKind = "heading" | "text" | "list" | "code" | "table" | "quote";
20
+
21
+ export interface Block {
22
+ /** `hash#occurrence` — stable across reflow, distinguishes duplicates. */
23
+ id: string;
24
+ kind: BlockKind;
25
+ /** Raw markdown of the block (trimmed, inner blank lines kept). */
26
+ text: string;
27
+ /** Hash of the normalized text — equal hash means "not changed". */
28
+ hash: string;
29
+ /** 0-based position in the document. */
30
+ index: number;
31
+ /** 1-based line number of the block's first line. */
32
+ line: number;
33
+ }
34
+
35
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
36
+ const HEADING_RE = /^ {0,3}#{1,6}\s/;
37
+ const QUOTE_RE = /^ {0,3}>\s?/;
38
+ const LIST_RE = /^ {0,3}(?:[-*+]|\d{1,9}[.)])\s/;
39
+ const TABLE_SEPARATOR_RE = /^ {0,3}\|?[\s:-]*-{3,}[\s:|-]*$/;
40
+
41
+ /** Normalize a block for hashing: reflow-insensitive, case-sensitive. */
42
+ export function normalizeBlockText(text: string): string {
43
+ return text
44
+ .split("\n")
45
+ .map((line) => line.trim())
46
+ .join(" ")
47
+ .replace(/\s+/g, " ")
48
+ .trim();
49
+ }
50
+
51
+ /** 12 hex chars of sha1 — short enough to read in an id, wide enough to not collide. */
52
+ export function hashBlockText(text: string): string {
53
+ return createHash("sha1").update(normalizeBlockText(text)).digest("hex").slice(0, 12);
54
+ }
55
+
56
+ function classify(lines: readonly string[]): BlockKind {
57
+ const first = lines[0] ?? "";
58
+ if (FENCE_RE.test(first)) return "code";
59
+ if (HEADING_RE.test(first)) return "heading";
60
+ if (QUOTE_RE.test(first)) return "quote";
61
+ if (lines.length >= 2 && first.includes("|") && TABLE_SEPARATOR_RE.test(lines[1] ?? "")) {
62
+ return "table";
63
+ }
64
+ if (LIST_RE.test(first)) return "list";
65
+ return "text";
66
+ }
67
+
68
+ interface Chunk {
69
+ lines: string[];
70
+ line: number;
71
+ }
72
+
73
+ /** Split markdown into chunks: blank-line separated, fence-aware. */
74
+ function splitChunks(markdown: string): Chunk[] {
75
+ const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
76
+ const chunks: Chunk[] = [];
77
+ let current: string[] = [];
78
+ let startLine = 1;
79
+ /** Open fence: its character and its opening run length. */
80
+ let fence: { char: string; length: number } | null = null;
81
+
82
+ const flush = (): void => {
83
+ if (current.length === 0) return;
84
+ chunks.push({ lines: current, line: startLine });
85
+ current = [];
86
+ };
87
+
88
+ for (let i = 0; i < lines.length; i += 1) {
89
+ const line = lines[i] ?? "";
90
+ const fenceMatch = FENCE_RE.exec(line);
91
+
92
+ if (fence) {
93
+ if (current.length === 0) startLine = i + 1;
94
+ current.push(line);
95
+ // Close only on a run of the same character at least as long as the
96
+ // opener (CommonMark): ``` inside a ~~~~ block is content.
97
+ if (
98
+ fenceMatch &&
99
+ fenceMatch[1]?.startsWith(fence.char) &&
100
+ fenceMatch[1].length >= fence.length
101
+ ) {
102
+ fence = null;
103
+ }
104
+ continue;
105
+ }
106
+
107
+ if (fenceMatch) {
108
+ if (current.length === 0) startLine = i + 1;
109
+ fence = { char: fenceMatch[1][0], length: fenceMatch[1].length };
110
+ current.push(line);
111
+ continue;
112
+ }
113
+
114
+ if (line.trim() === "") {
115
+ flush();
116
+ continue;
117
+ }
118
+
119
+ if (current.length === 0) startLine = i + 1;
120
+ current.push(line);
121
+ }
122
+
123
+ flush();
124
+ return chunks;
125
+ }
126
+
127
+ /**
128
+ * Parse plan markdown into blocks. An empty document yields no blocks; a
129
+ * document that is only blank lines yields none either (never a phantom block).
130
+ */
131
+ export function parseBlocks(markdown: string): Block[] {
132
+ const seen = new Map<string, number>();
133
+ return splitChunks(markdown).map((chunk, index) => {
134
+ const text = chunk.lines.join("\n").trim();
135
+ const hash = hashBlockText(text);
136
+ const occurrence = seen.get(hash) ?? 0;
137
+ seen.set(hash, occurrence + 1);
138
+ return {
139
+ id: `${hash}#${occurrence}`,
140
+ kind: classify(chunk.lines),
141
+ text,
142
+ hash,
143
+ index,
144
+ line: chunk.line,
145
+ };
146
+ });
147
+ }
148
+
149
+ /** One-line label for a block: its first line, clipped — used in feedback text. */
150
+ export function blockLabel(block: Block, maxLength = 80): string {
151
+ const first = (block.text.split("\n")[0] ?? "").trim();
152
+ return first.length > maxLength ? `${first.slice(0, maxLength - 1)}…` : first;
153
+ }
@@ -0,0 +1,144 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { parseBlocks } from "./blocks.js";
3
+ import { blockSimilarity, countChanged, diffBlocks } from "./diff.js";
4
+
5
+ const parse = (markdown: string) => parseBlocks(markdown);
6
+
7
+ describe("diffBlocks", () => {
8
+ it("reports everything unchanged for identical revisions", () => {
9
+ const doc = parse("alpha\n\nbeta\n\ngamma");
10
+ const entries = diffBlocks(doc, parse("alpha\n\nbeta\n\ngamma"));
11
+ expect(entries.map((entry) => entry.status)).toEqual(["unchanged", "unchanged", "unchanged"]);
12
+ expect(countChanged(entries)).toBe(0);
13
+ });
14
+
15
+ it("calls a reworded block modified, not added+removed", () => {
16
+ const before = parse("Write the parser first, then the server.");
17
+ const after = parse("Write the block parser first, then the HTTP server.");
18
+ const entries = diffBlocks(before, after);
19
+ expect(entries).toHaveLength(1);
20
+ expect(entries[0]?.status).toBe("modified");
21
+ expect(entries[0]?.prevId).toBe(before[0]?.id);
22
+ expect(entries[0]?.id).toBe(after[0]?.id);
23
+ });
24
+
25
+ it("reports an appended block as added", () => {
26
+ const before = parse("alpha\n\nbeta");
27
+ const after = parse("alpha\n\nbeta\n\ngamma");
28
+ const entries = diffBlocks(before, after);
29
+ expect(entries.map((entry) => entry.status)).toEqual(["unchanged", "unchanged", "added"]);
30
+ expect(entries[2]?.id).toBe(after[2]?.id);
31
+ });
32
+
33
+ it("reports a deleted block as removed, in the position it left", () => {
34
+ const before = parse("alpha\n\nbeta\n\ngamma");
35
+ const after = parse("alpha\n\ngamma");
36
+ const entries = diffBlocks(before, after);
37
+ expect(entries.map((entry) => entry.status)).toEqual(["unchanged", "removed", "unchanged"]);
38
+ expect(entries[1]?.id).toBe(before[1]?.id);
39
+ });
40
+
41
+ it("reports a block that only changed position as moved", () => {
42
+ const before = parse("alpha\n\nbeta");
43
+ const after = parse("beta\n\nalpha");
44
+ const entries = diffBlocks(before, after);
45
+ expect(entries).toHaveLength(2);
46
+ // Which of the two keeps the anchor is arbitrary; the contract is that
47
+ // exactly one is unchanged and the other is moved — never add+remove.
48
+ expect(entries.map((entry) => entry.status).sort()).toEqual(["moved", "unchanged"]);
49
+ expect(countChanged(entries)).toBe(1);
50
+ });
51
+
52
+ it("does not pair unrelated blocks as modified", () => {
53
+ const before = parse("Deploy the worker container.");
54
+ const after = parse("Buy milk and eggs.");
55
+ const entries = diffBlocks(before, after);
56
+ expect(entries.map((entry) => entry.status)).toEqual(["removed", "added"]);
57
+ });
58
+
59
+ it("handles a full rewrite without inventing modifications", () => {
60
+ const before = parse("one\n\ntwo\n\nthree");
61
+ const after = parse("alpha\n\nbeta\n\ngamma");
62
+ const entries = diffBlocks(before, after);
63
+ expect(countChanged(entries)).toBe(6);
64
+ expect(entries.some((entry) => entry.status === "unchanged")).toBe(false);
65
+ });
66
+
67
+ it("keeps a rotation as one move, not as edits", () => {
68
+ const before = parse("one\n\ntwo\n\nthree");
69
+ const after = parse("three\n\none\n\ntwo");
70
+ const entries = diffBlocks(before, after);
71
+ expect(entries.filter((entry) => entry.status === "modified")).toHaveLength(0);
72
+ expect(entries.filter((entry) => entry.status === "moved")).toHaveLength(1);
73
+ expect(entries.filter((entry) => entry.status === "unchanged")).toHaveLength(2);
74
+ expect(entries).toHaveLength(3);
75
+ });
76
+
77
+ it("keeps reading order: removals before the blocks that replace them", () => {
78
+ const before = parse("keep\n\nold block to delete\n\ntail");
79
+ const after = parse("keep\n\nnew block entirely\n\ntail");
80
+ const entries = diffBlocks(before, after);
81
+ expect(entries.map((entry) => entry.status)).toEqual([
82
+ "unchanged",
83
+ "removed",
84
+ "added",
85
+ "unchanged",
86
+ ]);
87
+ });
88
+
89
+ it("diffs against an empty previous revision as pure additions", () => {
90
+ const after = parse("alpha\n\nbeta");
91
+ const entries = diffBlocks([], after);
92
+ expect(entries.map((entry) => entry.status)).toEqual(["added", "added"]);
93
+ });
94
+ it("accounts for every old and new block exactly once across reorder/edit churn", () => {
95
+ let seed = 17;
96
+ const random = () => {
97
+ seed = (seed * 1103515245 + 12345) % 2147483648;
98
+ return seed / 2147483648;
99
+ };
100
+ const vocabulary = ["alpha step", "beta step", "gamma step", "delta step", "epsilon step"];
101
+ for (let round = 0; round < 80; round += 1) {
102
+ const before = vocabulary
103
+ .map((text) => ({ text, score: random() }))
104
+ .sort((a, b) => a.score - b.score)
105
+ .slice(0, 3 + Math.floor(random() * 3))
106
+ .map((entry) => entry.text);
107
+ const after = before.map((text) => (random() < 0.35 ? `${text} with detail` : text));
108
+ if (random() < 0.5) after.push("zeta step");
109
+ // Deterministic rotation instead of a biased random comparator.
110
+ const shift = Math.floor(random() * Math.max(after.length, 1));
111
+ after.push(...after.splice(0, shift));
112
+ const previous = parse(before.join("\n\n"));
113
+ const next = parse(after.join("\n\n"));
114
+ const entries = diffBlocks(previous, next);
115
+ expect(
116
+ entries.filter((entry) => entry.status !== "removed").map((entry) => entry.id),
117
+ ).toEqual(next.map((block) => block.id));
118
+ const coveredPrevious = entries.flatMap((entry) => {
119
+ if (entry.status === "added") return [];
120
+ if (entry.status === "unchanged") return [entry.id];
121
+ return entry.prevId ? [entry.prevId] : [];
122
+ });
123
+ expect(new Set(coveredPrevious).size).toBe(previous.length);
124
+ }
125
+ });
126
+ });
127
+
128
+ describe("blockSimilarity", () => {
129
+ it("is 1 for identical text and low for unrelated text", () => {
130
+ const a = parse("Write the block parser.")[0]!;
131
+ const b = parse("Write the block parser.")[0]!;
132
+ const c = parse("Completely different sentence about cooking.")[0]!;
133
+ expect(blockSimilarity(a, b)).toBe(1);
134
+ expect(blockSimilarity(a, c)).toBeLessThan(0.2);
135
+ });
136
+
137
+ it("works on CJK text (bigrams, not words)", () => {
138
+ const a = parse("先做块模型,再做服务器。")[0]!;
139
+ const b = parse("先做块模型,然后做服务器。")[0]!;
140
+ const c = parse("今天天气不错,出去走走。")[0]!;
141
+ expect(blockSimilarity(a, b)).toBeGreaterThan(0.5);
142
+ expect(blockSimilarity(a, c)).toBeLessThan(0.2);
143
+ });
144
+ });