cladogram 0.5.3 → 0.5.5-beta.1

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 (54) hide show
  1. package/README.md +25 -6
  2. package/bin/clado.js +17 -6
  3. package/docs/plugin-development.md +135 -0
  4. package/docs/plugin-ui.md +43 -0
  5. package/docs/release.md +14 -0
  6. package/package.json +7 -1
  7. package/plugins/agent/index.js +181 -0
  8. package/plugins/agent/style.css +105 -0
  9. package/plugins/brand/index.js +262 -0
  10. package/plugins/brand/style.css +162 -0
  11. package/plugins/directory/capabilities.json +27 -0
  12. package/plugins/directory/index.js +201 -0
  13. package/plugins/directory/style.css +59 -0
  14. package/plugins/view-controls/index.js +58 -0
  15. package/plugins/view-controls/style.css +66 -0
  16. package/skills/clado/SKILL.md +19 -15
  17. package/src/html/app-css.js +69 -47
  18. package/src/html/canvas-chain.js +7 -7
  19. package/src/html/canvas-focus.js +2 -4
  20. package/src/html/canvas-screenshot.js +199 -0
  21. package/src/html/canvas-ui.css +5 -9
  22. package/src/html/canvas-ui.js +35 -27
  23. package/src/html/page.js +11 -37
  24. package/src/html/plugin-assets.js +33 -0
  25. package/src/html/plugin-ui.css +188 -0
  26. package/src/html/plugin-ui.js +51 -0
  27. package/src/html/runtime-api.js +41 -0
  28. package/src/html/runtime.js +164 -87
  29. package/src/server/agent.js +223 -0
  30. package/src/server/assets/clado-plugin-sdk.js +111 -0
  31. package/src/server/assets/library-canvas.js +14 -10
  32. package/src/server/assets/library-plugin-bridge.js +84 -0
  33. package/src/server/assets/library-plugins.css +39 -0
  34. package/src/server/assets/library-plugins.js +200 -0
  35. package/src/server/assets/library.css +8 -6
  36. package/src/server/assets/library.html +3 -13
  37. package/src/server/assets/library.js +280 -47
  38. package/src/server/canvas-capture.js +47 -0
  39. package/src/server/export.js +6 -3
  40. package/src/server/mcp.js +40 -17
  41. package/src/server/plugin-capabilities.js +188 -0
  42. package/src/server/plugin-settings.js +117 -0
  43. package/src/server/plugins.js +236 -0
  44. package/src/server/workspace.js +222 -29
  45. package/src/skill/install.js +1 -1
  46. package/src/skill/targets.js +3 -3
  47. package/src/util/update.js +3 -2
  48. package/src/vendor/html-to-image.min.js +24 -0
  49. package/src/workspace/service.js +21 -13
  50. package/src/workspace/storage.js +88 -20
  51. package/templates/business-flow.mdc +1 -1
  52. package/templates/call-chain.mdc +1 -1
  53. package/templates/data-design.mdc +1 -1
  54. package/src/server/assets/tree.js +0 -26
@@ -0,0 +1,24 @@
1
+ /*! html-to-image 1.11.13 | https://github.com/bubkoo/html-to-image
2
+ MIT License
3
+
4
+ Copyright (c) 2017-2025 W.Y.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ */
24
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).htmlToImage={})}(this,(function(t){"use strict";function e(t,e,n,r){return new(n||(n=Promise))((function(i,o){function u(t){try{a(r.next(t))}catch(t){o(t)}}function c(t){try{a(r.throw(t))}catch(t){o(t)}}function a(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(u,c)}a((r=r.apply(t,e||[])).next())}))}function n(t,e){var n,r,i,o,u={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function c(c){return function(a){return function(c){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(u=0)),u;)try{if(n=1,r&&(i=2&c[0]?r.return:c[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,c[1])).done)return i;switch(r=0,i&&(c=[2&c[0],i.value]),c[0]){case 0:case 1:i=c;break;case 4:return u.label++,{value:c[1],done:!1};case 5:u.label++,r=c[1],c=[0];continue;case 7:c=u.ops.pop(),u.trys.pop();continue;default:if(!(i=u.trys,(i=i.length>0&&i[i.length-1])||6!==c[0]&&2!==c[0])){u=0;continue}if(3===c[0]&&(!i||c[1]>i[0]&&c[1]<i[3])){u.label=c[1];break}if(6===c[0]&&u.label<i[1]){u.label=i[1],i=c;break}if(i&&u.label<i[2]){u.label=i[2],u.ops.push(c);break}i[2]&&u.ops.pop(),u.trys.pop();continue}c=e.call(t,u)}catch(t){c=[6,t],r=0}finally{n=i=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,a])}}}var r,i=(r=0,function(){return r+=1,"u".concat("0000".concat((Math.random()*Math.pow(36,4)<<0).toString(36)).slice(-4)).concat(r)});function o(t){for(var e=[],n=0,r=t.length;n<r;n++)e.push(t[n]);return e}var u=null;function c(t){return void 0===t&&(t={}),u||(u=t.includeStyleProperties?t.includeStyleProperties:o(window.getComputedStyle(document.documentElement)))}function a(t,e){var n=(t.ownerDocument.defaultView||window).getComputedStyle(t).getPropertyValue(e);return n?parseFloat(n.replace("px","")):0}function s(t,e){void 0===e&&(e={});var n,r,i,o=e.width||(r=a(n=t,"border-left-width"),i=a(n,"border-right-width"),n.clientWidth+r+i),u=e.height||function(t){var e=a(t,"border-top-width"),n=a(t,"border-bottom-width");return t.clientHeight+e+n}(t);return{width:o,height:u}}var l=16384;function f(t,e){return void 0===e&&(e={}),t.toBlob?new Promise((function(n){t.toBlob(n,e.type?e.type:"image/png",e.quality?e.quality:1)})):new Promise((function(n){for(var r=window.atob(t.toDataURL(e.type?e.type:void 0,e.quality?e.quality:void 0).split(",")[1]),i=r.length,o=new Uint8Array(i),u=0;u<i;u+=1)o[u]=r.charCodeAt(u);n(new Blob([o],{type:e.type?e.type:"image/png"}))}))}function h(t){return new Promise((function(e,n){var r=new Image;r.onload=function(){r.decode().then((function(){requestAnimationFrame((function(){return e(r)}))}))},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=t}))}function d(t){return e(this,void 0,void 0,(function(){return n(this,(function(e){return[2,Promise.resolve().then((function(){return(new XMLSerializer).serializeToString(t)})).then(encodeURIComponent).then((function(t){return"data:image/svg+xml;charset=utf-8,".concat(t)}))]}))}))}function v(t,r,i){return e(this,void 0,void 0,(function(){var e,o,u;return n(this,(function(n){return e="http://www.w3.org/2000/svg",o=document.createElementNS(e,"svg"),u=document.createElementNS(e,"foreignObject"),o.setAttribute("width","".concat(r)),o.setAttribute("height","".concat(i)),o.setAttribute("viewBox","0 0 ".concat(r," ").concat(i)),u.setAttribute("width","100%"),u.setAttribute("height","100%"),u.setAttribute("x","0"),u.setAttribute("y","0"),u.setAttribute("externalResourcesRequired","true"),o.appendChild(u),u.appendChild(t),[2,d(o)]}))}))}var p=function(t,e){if(t instanceof e)return!0;var n=Object.getPrototypeOf(t);return null!==n&&(n.constructor.name===e.name||p(n,e))};function g(t,e,n,r){var i=".".concat(t,":").concat(e),o=n.cssText?function(t){var e=t.getPropertyValue("content");return"".concat(t.cssText," content: '").concat(e.replace(/'|"/g,""),"';")}(n):function(t,e){return c(e).map((function(e){var n=t.getPropertyValue(e),r=t.getPropertyPriority(e);return"".concat(e,": ").concat(n).concat(r?" !important":"",";")})).join(" ")}(n,r);return document.createTextNode("".concat(i,"{").concat(o,"}"))}function m(t,e,n,r){var o=window.getComputedStyle(t,n),u=o.getPropertyValue("content");if(""!==u&&"none"!==u){var c=i();try{e.className="".concat(e.className," ").concat(c)}catch(t){return}var a=document.createElement("style");a.appendChild(g(c,n,o,r)),e.appendChild(a)}}var w="application/font-woff",y="image/jpeg",b={woff:w,woff2:w,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:y,jpeg:y,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function S(t){var e=function(t){var e=/\.([^./]*?)$/g.exec(t);return e?e[1]:""}(t).toLowerCase();return b[e]||""}function E(t){return-1!==t.search(/^(data:)/)}function x(t,e){return"data:".concat(e,";base64,").concat(t)}function C(t,r,i){return e(this,void 0,void 0,(function(){var e,o;return n(this,(function(n){switch(n.label){case 0:return[4,fetch(t,r)];case 1:if(404===(e=n.sent()).status)throw new Error('Resource "'.concat(e.url,'" not found'));return[4,e.blob()];case 2:return o=n.sent(),[2,new Promise((function(t,n){var r=new FileReader;r.onerror=n,r.onloadend=function(){try{t(i({res:e,result:r.result}))}catch(t){n(t)}},r.readAsDataURL(o)}))]}}))}))}var P={};function R(t,r,i){return e(this,void 0,void 0,(function(){var e,o,u,c,a;return n(this,(function(n){switch(n.label){case 0:if(e=function(t,e,n){var r=t.replace(/\?.*/,"");return n&&(r=t),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),e?"[".concat(e,"]").concat(r):r}(t,r,i.includeQueryParams),null!=P[e])return[2,P[e]];i.cacheBust&&(t+=(/\?/.test(t)?"&":"?")+(new Date).getTime()),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,C(t,i.fetchRequestInit,(function(t){var e=t.res,n=t.result;return r||(r=e.headers.get("Content-Type")||""),function(t){return t.split(/,/)[1]}(n)}))];case 2:return u=n.sent(),o=x(u,r),[3,4];case 3:return c=n.sent(),o=i.imagePlaceholder||"",a="Failed to fetch resource: ".concat(t),c&&(a="string"==typeof c?c:c.message),a&&console.warn(a),[3,4];case 4:return P[e]=o,[2,o]}}))}))}function T(t){return e(this,void 0,void 0,(function(){var e;return n(this,(function(n){return"data:,"===(e=t.toDataURL())?[2,t.cloneNode(!1)]:[2,h(e)]}))}))}function A(t,r){return e(this,void 0,void 0,(function(){var e,i,o,u;return n(this,(function(n){switch(n.label){case 0:return t.currentSrc?(e=document.createElement("canvas"),i=e.getContext("2d"),e.width=t.clientWidth,e.height=t.clientHeight,null==i||i.drawImage(t,0,0,e.width,e.height),[2,h(e.toDataURL())]):(o=t.poster,u=S(o),[4,R(o,u,r)]);case 1:return[2,h(n.sent())]}}))}))}function k(t,r){var i;return e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return e.trys.push([0,3,,4]),(null===(i=null==t?void 0:t.contentDocument)||void 0===i?void 0:i.body)?[4,I(t.contentDocument.body,r,!0)]:[3,2];case 1:return[2,e.sent()];case 2:return[3,4];case 3:return e.sent(),[3,4];case 4:return[2,t.cloneNode(!1)]}}))}))}var L=function(t){return null!=t.tagName&&"SVG"===t.tagName.toUpperCase()};function N(t,e,n){return p(e,Element)&&(function(t,e,n){var r=e.style;if(r){var i=window.getComputedStyle(t);i.cssText?(r.cssText=i.cssText,r.transformOrigin=i.transformOrigin):c(n).forEach((function(n){var o=i.getPropertyValue(n);if("font-size"===n&&o.endsWith("px")){var u=Math.floor(parseFloat(o.substring(0,o.length-2)))-.1;o="".concat(u,"px")}p(t,HTMLIFrameElement)&&"display"===n&&"inline"===o&&(o="block"),"d"===n&&e.getAttribute("d")&&(o="path(".concat(e.getAttribute("d"),")")),r.setProperty(n,o,i.getPropertyPriority(n))}))}}(t,e,n),function(t,e,n){m(t,e,":before",n),m(t,e,":after",n)}(t,e,n),function(t,e){p(t,HTMLTextAreaElement)&&(e.innerHTML=t.value),p(t,HTMLInputElement)&&e.setAttribute("value",t.value)}(t,e),function(t,e){if(p(t,HTMLSelectElement)){var n=e,r=Array.from(n.children).find((function(e){return t.value===e.getAttribute("value")}));r&&r.setAttribute("selected","")}}(t,e)),e}function I(t,r,i){return e(this,void 0,void 0,(function(){return n(this,(function(u){return i||!r.filter||r.filter(t)?[2,Promise.resolve(t).then((function(t){return function(t,r){return e(this,void 0,void 0,(function(){return n(this,(function(e){return p(t,HTMLCanvasElement)?[2,T(t)]:p(t,HTMLVideoElement)?[2,A(t,r)]:p(t,HTMLIFrameElement)?[2,k(t,r)]:[2,t.cloneNode(L(t))]}))}))}(t,r)})).then((function(i){return function(t,r,i){var u,c;return e(this,void 0,void 0,(function(){var e;return n(this,(function(n){switch(n.label){case 0:return L(r)?[2,r]:(e=[],0===(e=null!=(a=t).tagName&&"SLOT"===a.tagName.toUpperCase()&&t.assignedNodes?o(t.assignedNodes()):p(t,HTMLIFrameElement)&&(null===(u=t.contentDocument)||void 0===u?void 0:u.body)?o(t.contentDocument.body.childNodes):o((null!==(c=t.shadowRoot)&&void 0!==c?c:t).childNodes)).length||p(t,HTMLVideoElement)?[2,r]:[4,e.reduce((function(t,e){return t.then((function(){return I(e,i)})).then((function(t){t&&r.appendChild(t)}))}),Promise.resolve())]);case 1:return n.sent(),[2,r]}var a}))}))}(t,i,r)})).then((function(e){return N(t,e,r)})).then((function(t){return function(t,r){return e(this,void 0,void 0,(function(){var e,i,o,u,c,a,s,l,f,h,d,v,p;return n(this,(function(n){switch(n.label){case 0:if(0===(e=t.querySelectorAll?t.querySelectorAll("use"):[]).length)return[2,t];i={},p=0,n.label=1;case 1:return p<e.length?(o=e[p],(u=o.getAttribute("xlink:href"))?(c=t.querySelector(u),a=document.querySelector(u),c||!a||i[u]?[3,3]:(s=i,l=u,[4,I(a,r,!0)])):[3,3]):[3,4];case 2:s[l]=n.sent(),n.label=3;case 3:return p++,[3,1];case 4:if((f=Object.values(i)).length){for(h="http://www.w3.org/1999/xhtml",(d=document.createElementNS(h,"svg")).setAttribute("xmlns",h),d.style.position="absolute",d.style.width="0",d.style.height="0",d.style.overflow="hidden",d.style.display="none",v=document.createElementNS(h,"defs"),d.appendChild(v),p=0;p<f.length;p++)v.appendChild(f[p]);t.appendChild(d)}return[2,t]}}))}))}(t,r)}))]:[2,null]}))}))}var D=/url\((['"]?)([^'"]+?)\1\)/g,H=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,M=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function F(t,r,i,o,u){return e(this,void 0,void 0,(function(){var e,c,a,s;return n(this,(function(n){switch(n.label){case 0:return n.trys.push([0,5,,6]),e=i?function(t,e){if(t.match(/^[a-z]+:\/\//i))return t;if(t.match(/^\/\//))return window.location.protocol+t;if(t.match(/^[a-z]+:/i))return t;var n=document.implementation.createHTMLDocument(),r=n.createElement("base"),i=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(i),e&&(r.href=e),i.href=t,i.href}(r,i):r,c=S(r),a=void 0,u?[4,u(e)]:[3,2];case 1:return s=n.sent(),a=x(s,c),[3,4];case 2:return[4,R(e,c,o)];case 3:a=n.sent(),n.label=4;case 4:return[2,t.replace((l=r,f=l.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1"),new RegExp("(url\\(['\"]?)(".concat(f,")(['\"]?\\))"),"g")),"$1".concat(a,"$3"))];case 5:return n.sent(),[3,6];case 6:return[2,t]}var l,f}))}))}function V(t){return-1!==t.search(D)}function q(t,r,i){return e(this,void 0,void 0,(function(){var e,o;return n(this,(function(n){return V(t)?(e=function(t,e){var n=e.preferredFontFormat;return n?t.replace(M,(function(t){for(;;){var e=H.exec(t)||[],r=e[0],i=e[2];if(!i)return"";if(i===n)return"src: ".concat(r,";")}})):t}(t,i),o=function(t){var e=[];return t.replace(D,(function(t,n,r){return e.push(r),t})),e.filter((function(t){return!E(t)}))}(e),[2,o.reduce((function(t,e){return t.then((function(t){return F(t,e,r,i)}))}),Promise.resolve(e))]):[2,t]}))}))}function U(t,r,i){var o;return e(this,void 0,void 0,(function(){var e,u;return n(this,(function(n){switch(n.label){case 0:return(e=null===(o=r.style)||void 0===o?void 0:o.getPropertyValue(t))?[4,q(e,null,i)]:[3,2];case 1:return u=n.sent(),r.style.setProperty(t,u,r.style.getPropertyPriority(t)),[2,!0];case 2:return[2,!1]}}))}))}function j(t,r){return e(this,void 0,void 0,(function(){var e,i;return n(this,(function(n){switch(n.label){case 0:return[4,U("background",t,r)];case 1:return n.sent()?[3,3]:[4,U("background-image",t,r)];case 2:n.sent(),n.label=3;case 3:return[4,U("mask",t,r)];case 4:return(i=n.sent())?[3,6]:[4,U("-webkit-mask",t,r)];case 5:i=n.sent(),n.label=6;case 6:return(e=i)?[3,8]:[4,U("mask-image",t,r)];case 7:e=n.sent(),n.label=8;case 8:return e?[3,10]:[4,U("-webkit-mask-image",t,r)];case 9:n.sent(),n.label=10;case 10:return[2]}}))}))}function O(t,r){return e(this,void 0,void 0,(function(){var e,i,o;return n(this,(function(n){switch(n.label){case 0:return(e=p(t,HTMLImageElement))&&!E(t.src)||p(t,SVGImageElement)&&!E(t.href.baseVal)?[4,R(i=e?t.src:t.href.baseVal,S(i),r)]:[2];case 1:return o=n.sent(),[4,new Promise((function(n,i){t.onload=n,t.onerror=r.onImageErrorHandler?function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];try{n(r.onImageErrorHandler.apply(r,t))}catch(t){i(t)}}:i;var u=t;u.decode&&(u.decode=n),"lazy"===u.loading&&(u.loading="eager"),e?(t.srcset="",t.src=o):t.href.baseVal=o}))];case 2:return n.sent(),[2]}}))}))}function B(t,r){return e(this,void 0,void 0,(function(){var e,i;return n(this,(function(n){switch(n.label){case 0:return e=o(t.childNodes),i=e.map((function(t){return z(t,r)})),[4,Promise.all(i).then((function(){return t}))];case 1:return n.sent(),[2]}}))}))}function z(t,r){return e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return p(t,Element)?[4,j(t,r)]:[3,4];case 1:return e.sent(),[4,O(t,r)];case 2:return e.sent(),[4,B(t,r)];case 3:e.sent(),e.label=4;case 4:return[2]}}))}))}var W={};function $(t){return e(this,void 0,void 0,(function(){var e,r;return n(this,(function(n){switch(n.label){case 0:return null!=(e=W[t])?[2,e]:[4,fetch(t)];case 1:return[4,n.sent().text()];case 2:return r=n.sent(),e={url:t,cssText:r},W[t]=e,[2,e]}}))}))}function G(t,r){return e(this,void 0,void 0,(function(){var i,o,u,c,a=this;return n(this,(function(s){return i=t.cssText,o=/url\(["']?([^"')]+)["']?\)/g,u=i.match(/url\([^)]+\)/g)||[],c=u.map((function(u){return e(a,void 0,void 0,(function(){var e;return n(this,(function(n){return(e=u.replace(o,"$1")).startsWith("https://")||(e=new URL(e,t.url).href),[2,C(e,r.fetchRequestInit,(function(t){var e=t.result;return i=i.replace(u,"url(".concat(e,")")),[u,e]}))]}))}))})),[2,Promise.all(c).then((function(){return i}))]}))}))}function _(t){if(null==t)return[];for(var e=[],n=t.replace(/(\/\*[\s\S]*?\*\/)/gi,""),r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");;){if(null===(u=r.exec(n)))break;e.push(u[0])}n=n.replace(r,"");for(var i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");;){var u;if(null===(u=i.exec(n))){if(null===(u=o.exec(n)))break;i.lastIndex=o.lastIndex}else o.lastIndex=i.lastIndex;e.push(u[0])}return e}function J(t,r){return e(this,void 0,void 0,(function(){var e,i;return n(this,(function(n){return e=[],i=[],t.forEach((function(e){if("cssRules"in e)try{o(e.cssRules||[]).forEach((function(t,n){if(t.type===CSSRule.IMPORT_RULE){var o=n+1,u=$(t.href).then((function(t){return G(t,r)})).then((function(t){return _(t).forEach((function(t){try{e.insertRule(t,t.startsWith("@import")?o+=1:e.cssRules.length)}catch(e){console.error("Error inserting rule from remote css",{rule:t,error:e})}}))})).catch((function(t){console.error("Error loading remote css",t.toString())}));i.push(u)}}))}catch(o){var n=t.find((function(t){return null==t.href}))||document.styleSheets[0];null!=e.href&&i.push($(e.href).then((function(t){return G(t,r)})).then((function(t){return _(t).forEach((function(t){n.insertRule(t,n.cssRules.length)}))})).catch((function(t){console.error("Error loading remote stylesheet",t)}))),console.error("Error inlining remote css file",o)}})),[2,Promise.all(i).then((function(){return t.forEach((function(t){if("cssRules"in t)try{o(t.cssRules||[]).forEach((function(t){e.push(t)}))}catch(e){console.error("Error while reading CSS rules from ".concat(t.href),e)}})),e}))]}))}))}function Q(t){return t.filter((function(t){return t.type===CSSRule.FONT_FACE_RULE})).filter((function(t){return V(t.style.getPropertyValue("src"))}))}function X(t,r){return e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:if(null==t.ownerDocument)throw new Error("Provided element is not within a Document");return[4,J(o(t.ownerDocument.styleSheets),r)];case 1:return[2,Q(e.sent())]}}))}))}function K(t){return t.trim().replace(/["']/g,"")}function Y(t,r){return e(this,void 0,void 0,(function(){var e,i;return n(this,(function(n){switch(n.label){case 0:return[4,X(t,r)];case 1:return e=n.sent(),i=function(t){var e=new Set;return function t(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach((function(t){e.add(K(t))})),Array.from(n.children).forEach((function(e){e instanceof HTMLElement&&t(e)}))}(t),e}(t),[4,Promise.all(e.filter((function(t){return i.has(K(t.style.fontFamily))})).map((function(t){var e=t.parentStyleSheet?t.parentStyleSheet.href:null;return q(t.cssText,e,r)})))];case 2:return[2,n.sent().join("\n")]}}))}))}function Z(t,r){return e(this,void 0,void 0,(function(){var e,i,o,u,c;return n(this,(function(n){switch(n.label){case 0:return null==r.fontEmbedCSS?[3,1]:(i=r.fontEmbedCSS,[3,5]);case 1:return r.skipFonts?(o=null,[3,4]):[3,2];case 2:return[4,Y(t,r)];case 3:o=n.sent(),n.label=4;case 4:i=o,n.label=5;case 5:return(e=i)&&(u=document.createElement("style"),c=document.createTextNode(e),u.appendChild(c),t.firstChild?t.insertBefore(u,t.firstChild):t.appendChild(u)),[2]}}))}))}function tt(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){var e,i,o,u;return n(this,(function(n){switch(n.label){case 0:return e=s(t,r),i=e.width,o=e.height,[4,I(t,r,!0)];case 1:return[4,Z(u=n.sent(),r)];case 2:return n.sent(),[4,z(u,r)];case 3:return n.sent(),function(t,e){var n=t.style;e.backgroundColor&&(n.backgroundColor=e.backgroundColor),e.width&&(n.width="".concat(e.width,"px")),e.height&&(n.height="".concat(e.height,"px"));var r=e.style;null!=r&&Object.keys(r).forEach((function(t){n[t]=r[t]}))}(u,r),[4,v(u,i,o)];case 4:return[2,n.sent()]}}))}))}function et(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){var e,i,o,u,c,a,f,d,v;return n(this,(function(n){switch(n.label){case 0:return e=s(t,r),i=e.width,o=e.height,[4,tt(t,r)];case 1:return[4,h(n.sent())];case 2:return u=n.sent(),c=document.createElement("canvas"),a=c.getContext("2d"),f=r.pixelRatio||function(){var t,e;try{e=process}catch(t){}var n=e&&e.env?e.env.devicePixelRatio:null;return n&&(t=parseInt(n,10),Number.isNaN(t)&&(t=1)),t||window.devicePixelRatio||1}(),d=r.canvasWidth||i,v=r.canvasHeight||o,c.width=d*f,c.height=v*f,r.skipAutoScale||function(t){(t.width>l||t.height>l)&&(t.width>l&&t.height>l?t.width>t.height?(t.height*=l/t.width,t.width=l):(t.width*=l/t.height,t.height=l):t.width>l?(t.height*=l/t.width,t.width=l):(t.width*=l/t.height,t.height=l))}(c),c.style.width="".concat(d),c.style.height="".concat(v),r.backgroundColor&&(a.fillStyle=r.backgroundColor,a.fillRect(0,0,c.width,c.height)),a.drawImage(u,0,0,c.width,c.height),[2,c]}}))}))}t.getFontEmbedCSS=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){return n(this,(function(e){return[2,Y(t,r)]}))}))},t.toBlob=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return[4,et(t,r)];case 1:return[4,f(e.sent())];case 2:return[2,e.sent()]}}))}))},t.toCanvas=et,t.toJpeg=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return[4,et(t,r)];case 1:return[2,e.sent().toDataURL("image/jpeg",r.quality||1)]}}))}))},t.toPixelData=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){var e,i,o,u;return n(this,(function(n){switch(n.label){case 0:return e=s(t,r),i=e.width,o=e.height,[4,et(t,r)];case 1:return u=n.sent(),[2,u.getContext("2d").getImageData(0,0,i,o).data]}}))}))},t.toPng=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return[4,et(t,r)];case 1:return[2,e.sent().toDataURL()]}}))}))},t.toSvg=tt}));
@@ -3,7 +3,7 @@ import { resolve } from 'node:path';
3
3
  import { parseDocument, splitFrontMatter } from '../core/parse.js';
4
4
  import { versionOf } from './documents.js';
5
5
  import { treeOf, records, findNode, siblings, samePath, insidePath, checkTitle, checkBody, serializeTree, replaceNodeBody, withMetadata } from './tree.js';
6
- import { ancestorTemplateContexts, contextFor, initialize, locked, mergeAncestorTemplates, snapshot, safeFile, fail, commit, userTemplateContext } from './storage.js';
6
+ import { ancestorTemplateContexts, contextFor, discoverWorkspaces, initialize, lockedAsync, mergeAncestorTemplates, snapshot, safeFile, fail, commit, userTemplateContext } from './storage.js';
7
7
  import { allReferences, linkHref, resolveReference, rewriteReferences } from './references.js';
8
8
  import { editContent, paragraphs, paragraphLocations, contentLocation } from './content.js';
9
9
  import { markdownLinks } from '../core/links.js';
@@ -371,7 +371,7 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
371
371
  const ancestor = mergeAncestorTemplates(contexts);
372
372
  return { ancestorRoots: contexts.map(context => context.templates), ancestorTemplates: ancestor.templates, ancestorOrigins: ancestor.origins, userTemplateRoot: user.templates };
373
373
  }
374
- function diagnostics(args) {
374
+ async function diagnostics(args) {
375
375
  try {
376
376
  const ctx = contextFor(scope, args?.workspace, documentRoot);
377
377
  if (!existsSync(ctx.documents)) fail('工作区尚未初始化,无法检查全部文档。', 404);
@@ -381,30 +381,38 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
381
381
  const state = snapshot(ctx), userState = snapshot(user), { ancestorRoots, ancestorTemplates, ancestorOrigins } = layers;
382
382
  const ancestorVersion = versionOf(JSON.stringify([...ancestorTemplates].map(([file, source]) => [file, ancestorOrigins.get(file), versionOf(source)])));
383
383
  const key = JSON.stringify([ctx.workspace, ctx.documents, ctx.templates, user.templates, state.version, userState.version, ancestorRoots, ancestorVersion]);
384
- if (diagnosticCache.has(key)) return diagnosticCache.get(key);
384
+ const cached = diagnosticCache.get(ctx.workspace);
385
+ if (cached?.key === key) return cached.report;
385
386
  const all = fullDiagnostics(ctx, { ...state, ...layers, userTemplates: userState.templates }), summary = summarizeDiagnostics(all);
386
387
  const report = { diagnosticSummary: summary, diagnosticsComplete: true, valid: summary.error === 0, diagnosticsVersion: { workspace: state.version, userTemplates: userState.version, ancestorTemplates: ancestorVersion }, diagnosticsScope: { workspace: ctx.workspace, documentRoot: ctx.documents, projectTemplateRoot: ctx.templates, ancestorTemplateRoots: ancestorRoots, userTemplateRoot: user.templates }, diagnostics: all };
387
- diagnosticCache.clear(); diagnosticCache.set(key, report); return report;
388
+ diagnosticCache.delete(ctx.workspace);
389
+ diagnosticCache.set(ctx.workspace, { key, report });
390
+ if (diagnosticCache.size > 64) diagnosticCache.delete(diagnosticCache.keys().next().value);
391
+ return report;
388
392
  };
389
- return locked(ctx, () => ctx.state === user.state ? collect() : locked(user, collect));
393
+ return await lockedAsync(ctx, collect);
390
394
  } catch (error) {
391
395
  return { diagnostics: [], diagnosticSummary: null, diagnosticsComplete: false, valid: null, diagnosticFailure: { message: error.message, status: error.status || 500 } };
392
396
  }
393
397
  }
394
- function invoke(tool, args) {
398
+ async function invoke(tool, args) {
395
399
  const ctx = contextFor(scope, args.workspace, documentRoot);
396
- if (tool === 'clado_workspace' && args.action === 'init') initialize(ctx);
397
- if (!existsSync(ctx.documents)) fail('工作区尚未初始化,请先调用 clado_workspace action:init。', 404);
400
+ if (tool === 'clado_workspace' && args.action === 'workspaces') {
401
+ return { workspace: ctx.workspace, scope, workspaces: discoverWorkspaces(scope, documentRoot) };
402
+ }
398
403
  if (args.from !== undefined && (tool !== 'clado_templates' || args.action !== 'pull')) fail('from 仅用于 template.pull。');
399
404
  const user = userTemplateContext();
400
- const layers = templateLayers(ctx, user);
401
- const run = () => {
405
+ const needsUserLock = ctx.state !== user.state && tool === 'clado_templates' && (args.scope === 'user' || args.action === 'push');
406
+ const execute = () => {
407
+ if (tool === 'clado_workspace' && args.action === 'init') initialize(ctx, { alreadyLocked: true });
408
+ if (!existsSync(ctx.documents)) fail('工作区尚未初始化,请先调用 clado_workspace action:init。', 404);
409
+ const layers = templateLayers(ctx, user);
402
410
  const userState = snapshot(user), { ancestorRoots } = layers;
403
411
  const state = { ...snapshot(ctx), ...layers, userTemplates: userState.templates };
404
412
  const common = { workspace: ctx.workspace, workspaceVersion: state.version, userTemplateRoot: user.templates, userTemplateVersion: userState.version };
405
413
  if (tool === 'clado_workspace') {
406
414
  if (args.action === 'selection') {
407
- const selection = ctx.workspace === scope ? readSelection?.() : null;
415
+ const selection = readSelection?.(ctx.workspace) || null;
408
416
  return { ...common, ...projectSelection(state, selection) };
409
417
  }
410
418
  if (args.action === 'init' || args.action === 'inspect') return { ...common, documentRoot: ctx.documents, templateRoot: ctx.templates, ancestorTemplateRoots: ancestorRoots, documents: [...state.documents].map(([file, source]) => ({ file, version: versionOf(source), title: parseDocument(source).doc.title })) };
@@ -414,7 +422,7 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
414
422
  for (const [file, source] of state.documents) for (const record of records(treeOf(source, file))) if ((file + '\n' + record.node.title + '\n' + record.node.content).toLowerCase().includes(query)) hits.push({ file, ...publicNode(record, args.includeContent === true) });
415
423
  return { ...common, total: hits.length, nodes: hits.slice(args.offset || 0, (args.offset || 0) + (args.limit || 50)) };
416
424
  }
417
- fail('workspace action 支持 init / inspect / validate / search / selection。');
425
+ fail('workspace action 支持 init / inspect / validate / search / selection / workspaces。');
418
426
  }
419
427
  if (tool === 'clado_templates' && ['list', 'read'].includes(args.action)) {
420
428
  const scope = args.scope || 'project', visible = scope === 'user' ? { templates: new Map(), userTemplates: userState.templates, userTemplateRoot: user.templates } : state;
@@ -511,7 +519,7 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
511
519
  const changes = commit(ctx, state, candidate, state.version);
512
520
  return { ...common, workspaceVersion: snapshot(ctx).version, changes, results: locations, diagnostics };
513
521
  };
514
- return locked(ctx, () => ctx.state === user.state ? run() : locked(user, run));
522
+ return await lockedAsync(ctx, () => needsUserLock ? lockedAsync(user, execute) : execute());
515
523
  }
516
524
  return Object.assign(invoke, { diagnostics });
517
525
  }
@@ -1,9 +1,12 @@
1
1
  import { readFileSync, writeFileSync, readdirSync, existsSync, mkdirSync, realpathSync, statSync, openSync, closeSync, unlinkSync, renameSync } from 'node:fs';
2
- import { resolve, dirname, join, relative, sep, isAbsolute } from 'node:path';
2
+ import { resolve, dirname, basename, join, relative, sep, isAbsolute } from 'node:path';
3
3
  import { randomBytes } from 'node:crypto';
4
4
  import { DocumentError, versionOf } from './documents.js';
5
5
  import { installUserTemplates, templateName } from '../skill/templates.js';
6
6
 
7
+ const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
8
+ const lockQueues = new Map();
9
+
7
10
  export function userTemplateContext() {
8
11
  const { state, templates } = installUserTemplates({ onlyIfMissing: true });
9
12
  return { workspace: state, documents: null, templates, state };
@@ -21,19 +24,19 @@ export function safeFile(root, file, kind = 'document') {
21
24
  }
22
25
  export function contextFor(scope, workspace, documentRoot) {
23
26
  if (typeof workspace !== 'string' || !isAbsolute(workspace)) fail('每次工具调用必须提供 workspace 的绝对路径。');
24
- const path = resolve(workspace);
25
- if (!contained(scope, path)) fail('工作区超出 serve 启动目录。', 403);
27
+ const scopeRoot = resolve(scope), path = resolve(workspace);
28
+ if (!contained(scopeRoot, path)) fail('工作区超出 serve 启动目录。', 403);
26
29
  let ancestor = path; while (!existsSync(ancestor)) ancestor = dirname(ancestor);
27
- if (!contained(realpathSync(scope), realpathSync(ancestor))) fail('工作区符号链接指向启动目录之外。', 403);
30
+ if (!contained(realpathSync(scopeRoot), realpathSync(ancestor))) fail('工作区符号链接指向启动目录之外。', 403);
28
31
  const state = join(path, '.clado'), templates = join(state, 'templates');
29
- const boundary = existsSync(path) ? realpathSync(path) : realpathSync(scope);
32
+ const boundary = existsSync(path) ? realpathSync(path) : realpathSync(scopeRoot);
30
33
  for (const child of [state, templates]) {
31
34
  let ancestor = child; while (!existsSync(ancestor)) ancestor = dirname(ancestor);
32
35
  if (!contained(boundary, realpathSync(ancestor))) fail('工作区内部目录指向其他工作区。', 403);
33
36
  }
34
- let documents = path === scope && documentRoot ? documentRoot : join(state, 'doc');
37
+ let documents = path === scopeRoot && documentRoot ? documentRoot : join(state, 'doc');
35
38
  const config = join(state, 'workspace.json');
36
- if (!documentRoot && existsSync(config)) {
39
+ if ((path !== scopeRoot || !documentRoot) && existsSync(config)) {
37
40
  const data = JSON.parse(readFileSync(config, 'utf8'));
38
41
  if (!['.', '.clado/doc'].includes(data.documentRoot)) fail('工作区配置无效。', 422);
39
42
  documents = resolve(path, data.documentRoot);
@@ -44,6 +47,34 @@ export function contextFor(scope, workspace, documentRoot) {
44
47
  }
45
48
  return { workspace: path, documents, templates, state };
46
49
  }
50
+ export function discoverWorkspaces(scope, rootDocumentRoot) {
51
+ const root = resolve(scope), items = [], seen = new Set();
52
+ const push = dir => {
53
+ const normalized = resolve(dir);
54
+ if (seen.has(normalized)) return;
55
+ seen.add(normalized);
56
+ try {
57
+ const ctx = contextFor(root, normalized, rootDocumentRoot);
58
+ const id = relative(root, normalized).split(sep).join('/');
59
+ items.push({ id, name: basename(normalized), workspace: ctx.workspace, documentRoot: ctx.documents, documents: fileMap(ctx.documents).size });
60
+ } catch {}
61
+ };
62
+ push(root);
63
+ const walk = (directory, depth = 0) => {
64
+ if (depth > 6 || items.length >= 200 || !existsSync(directory)) return;
65
+ let entries;
66
+ try { entries = readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)); }
67
+ catch { return; }
68
+ for (const entry of entries) {
69
+ if (!entry.isDirectory() || entry.name.startsWith('.') || ['node_modules', 'dist'].includes(entry.name)) continue;
70
+ const full = join(directory, entry.name);
71
+ if (existsSync(join(full, '.clado', 'workspace.json')) || existsSync(join(full, '.clado', 'doc'))) push(full);
72
+ walk(full, depth + 1);
73
+ }
74
+ };
75
+ walk(root, 0);
76
+ return items;
77
+ }
47
78
  export function ancestorTemplateContexts(workspace, user) {
48
79
  const contexts = [];
49
80
  let directory = dirname(workspace);
@@ -60,7 +91,7 @@ export function ancestorTemplateContexts(workspace, user) {
60
91
  export function mergeAncestorTemplates(contexts) {
61
92
  const templates = new Map(), origins = new Map();
62
93
  for (const context of contexts) {
63
- const files = locked(context, () => templateFiles(context.templates));
94
+ const files = templateFiles(context.templates);
64
95
  for (const [file, source] of files) {
65
96
  if (templates.has(file)) continue;
66
97
  templates.set(file, source);
@@ -69,21 +100,23 @@ export function mergeAncestorTemplates(contexts) {
69
100
  }
70
101
  return { templates, origins };
71
102
  }
72
- export function initialize(ctx) {
103
+ export function initialize(ctx, { alreadyLocked = false } = {}) {
73
104
  const config = join(ctx.state, 'workspace.json');
74
105
  const first = !existsSync(config) || !existsSync(ctx.templates);
75
106
  const user = userTemplateContext();
76
107
  mkdirSync(ctx.workspace, { recursive: true }); mkdirSync(ctx.documents, { recursive: true }); mkdirSync(ctx.templates, { recursive: true });
77
108
  if (!first) return;
78
- const defaults = ctx.state === user.state ? new Map() : locked(user, () => templateFiles(user.templates));
109
+ const defaults = ctx.state === user.state ? new Map() : templateFiles(user.templates);
79
110
  const inherited = mergeAncestorTemplates(ancestorTemplateContexts(ctx.workspace, user)).templates;
80
- locked(ctx, () => {
111
+ const write = () => {
81
112
  for (const [name, source] of new Map([...defaults, ...inherited])) {
82
113
  const file = safeFile(ctx.templates, name, 'template');
83
114
  if (!existsSync(file)) atom(file, source);
84
115
  }
85
116
  if (!existsSync(config)) atom(config, JSON.stringify({ documentRoot: ctx.documents === ctx.workspace ? '.' : '.clado/doc' }, null, 2) + '\n');
86
- });
117
+ };
118
+ if (alreadyLocked) write();
119
+ else locked(ctx, write);
87
120
  }
88
121
  export function templateFiles(root) {
89
122
  const files = new Map();
@@ -132,19 +165,54 @@ function recover(ctx) {
132
165
  }
133
166
  unlinkSync(journal);
134
167
  }
135
- export function locked(ctx, callback) {
136
- if (!existsSync(ctx.state)) mkdirSync(ctx.state, { recursive: true });
137
- const lock = join(ctx.state, '.mcp-lock'); let fd;
138
- try { fd = openSync(lock, 'wx', 0o600); }
168
+ function tryAcquireLock(lock) {
169
+ try { return openSync(lock, 'wx', 0o600); }
139
170
  catch (error) {
140
171
  if (error.code !== 'EEXIST') throw error;
141
172
  let stale = false;
142
- try { const owner = JSON.parse(readFileSync(lock, 'utf8')); if (!Number.isInteger(owner.pid) || owner.pid < 1) throw new Error(); try { process.kill(owner.pid, 0); } catch (e) { stale = e.code === 'ESRCH'; } } catch {}
143
- if (!stale) fail('工作区正在被另一个操作使用,请稍后重新读取。', 409);
144
- unlinkSync(lock); try { fd = openSync(lock, 'wx', 0o600); } catch { fail('工作区正在被另一个操作使用。', 409); }
173
+ try {
174
+ const owner = JSON.parse(readFileSync(lock, 'utf8'));
175
+ if (!Number.isInteger(owner.pid) || owner.pid < 1) throw new Error();
176
+ try { process.kill(owner.pid, 0); } catch (e) { stale = e.code === 'ESRCH'; }
177
+ } catch {}
178
+ if (!stale) return null;
179
+ try { unlinkSync(lock); } catch (e) { if (e.code !== 'ENOENT') return null; }
180
+ try { return openSync(lock, 'wx', 0o600); } catch (e) { if (e.code === 'EEXIST') return null; throw e; }
181
+ }
182
+ }
183
+ export function locked(ctx, callback, { timeoutMs = 1500 } = {}) {
184
+ if (!existsSync(ctx.state)) mkdirSync(ctx.state, { recursive: true });
185
+ const lock = join(ctx.state, '.mcp-lock');
186
+ const deadline = Date.now() + timeoutMs;
187
+ let fd = tryAcquireLock(lock);
188
+ while (fd === null && Date.now() < deadline) {
189
+ Atomics.wait(waitBuffer, 0, 0, 20);
190
+ fd = tryAcquireLock(lock);
145
191
  }
192
+ if (fd === null) fail('工作区正在被另一个操作使用,请稍后重新读取。', 409);
146
193
  try { writeFileSync(fd, JSON.stringify({ pid: process.pid })); recover(ctx); return callback(); }
147
- finally { closeSync(fd); unlinkSync(lock); }
194
+ finally { closeSync(fd); try { unlinkSync(lock); } catch {} }
195
+ }
196
+ export function lockedAsync(ctx, callback, { timeoutMs = 2500 } = {}) {
197
+ const key = resolve(ctx.state);
198
+ const previous = lockQueues.get(key) || Promise.resolve();
199
+ const run = previous.catch(() => {}).then(async () => {
200
+ if (!existsSync(ctx.state)) mkdirSync(ctx.state, { recursive: true });
201
+ const lock = join(ctx.state, '.mcp-lock');
202
+ const deadline = Date.now() + timeoutMs;
203
+ let fd = tryAcquireLock(lock), delay = 15;
204
+ while (fd === null && Date.now() < deadline) {
205
+ await new Promise(r => setTimeout(r, delay));
206
+ delay = Math.min(50, delay + 10);
207
+ fd = tryAcquireLock(lock);
208
+ }
209
+ if (fd === null) fail('工作区正在被另一个操作使用,请稍后重新读取。', 409);
210
+ try { writeFileSync(fd, JSON.stringify({ pid: process.pid })); recover(ctx); return await callback(); }
211
+ finally { closeSync(fd); try { unlinkSync(lock); } catch {} }
212
+ });
213
+ const tail = run.catch(() => {}).finally(() => { if (lockQueues.get(key) === tail) lockQueues.delete(key); });
214
+ lockQueues.set(key, tail);
215
+ return run;
148
216
  }
149
217
  export function commit(ctx, before, after, expectedVersion) {
150
218
  if (expectedVersion !== before.version || snapshot(ctx).version !== before.version) fail('工作区版本已变化,请重新读取并合并后重试。', 409, { code: 'VERSION_CONFLICT', currentVersion: snapshot(ctx).version });
@@ -5,7 +5,7 @@ purpose: 将一个业务场景讲清楚:谁在什么条件下做什么,成
5
5
  hard_constraints:
6
6
  - 一级标题是有明确职责的业务阶段、参与方动作或稳定业务状态,不能用Java类方法冒充业务步骤。
7
7
  - 第一张卡说明触发者、前提和本场景目标;二级标题解释阶段内部动作、条件与结果,三级至六级只展开所属分支。
8
- - 实际进入下一阶段的地方建立内链,文字说明触发条件与携带的信息;主路径、拒绝和提前结束都应可顺着读通。
8
+ - 实际进入下一阶段的地方从具体步骤正文、表格行或流程节点建立内链,文字说明触发条件与携带的信息;避免在卡片末尾单独追加裸的卡片连卡片,主路径、拒绝和提前结束都应可顺着读通。
9
9
  - 每张卡说明谁操作、依据什么、如何反馈、改变哪些业务状态、失败时谁接手;不要只列节点名称。
10
10
  - 层级是包含关系,正文内链才表达流转;每个一级卡应参与真实跨卡关系,单卡豁免。
11
11
  - 同一动作的互斥结果并列写清,不画成同时执行;普通返回用文字说明。
@@ -28,7 +28,7 @@ hard_constraints:
28
28
  - 不另附一份整方法“核心编排”,不把每条逻辑机械翻译成代码,不用一张巨大Mermaid代替方法和逻辑节点。
29
29
  - 持久化按真实技术栈组织;Java/MyBatis使用Repository实现、DAO接口方法和独立Mapper.xml#语句ID卡,XML卡解释SQL、参数绑定与结果映射;其他技术栈不强套这些层次。
30
30
  - 类型、泛型、XML标签和带尖括号的协议占位符放在行内代码或围栏中,避免正文被当作HTML;标题、段落、表格、围栏之间保留空行。
31
- - 多卡画布的每张卡至少参与一条真实跨卡关系;单卡豁免。跨文档跳转用于导航,不代替本画布的连线,不能为消除孤立卡而虚构调用。
31
+ - 多卡画布的每张卡至少参与一条真实跨卡关系;单卡豁免。跨卡连接应从具体内容行出发(优先用代码行、表格数据行、Mermaid节点或步骤正文内的行内链接),避免在卡片末尾单独追加裸的卡片连卡片。跨文档跳转用于导航,不代替本画布的连线,不能为消除孤立卡而虚构调用。
32
32
  soft_constraints:
33
33
  - 文字先说明当前逻辑,局部代码、表格或小图再解释需要精确表达的细节,不要求每个步骤都有图和代码。
34
34
  - 步骤标题优先使用清楚的动作或判断;正文尽量让读者不翻源代码也能理解当前步骤的目的和出口。
@@ -14,7 +14,7 @@ hard_constraints:
14
14
  - DDL与迁移放在所属节点的代码围栏,解释既有数据如何兼容、失败如何识别、如何回退及验证,不能只给建表语句。
15
15
  - SQL参数、字段、状态与接口和方法文档保持一致;调用链链接到本数据契约,而不重复维护另一份定义。
16
16
  - 表格与小型ER图服务当前对象关系,复杂规则用分层文字说明;不要用一张大图替代可修改的节点。
17
- - 多卡画布每张卡需参与真实数据关系或迁移依赖,单卡豁免;不要伪造外键或调用来凑连接。
17
+ - 多卡画布每张卡需参与真实数据关系或迁移依赖,单卡豁免;关系连线优先从字段表格行、DDL/SQL代码行或正文行内说明出发,避免裸的卡片连卡片,不要伪造外键或调用来凑连接。
18
18
  soft_constraints:
19
19
  - 使用“🟩 新增”“🟨 修改”“🟥 删除”标实际变更,“🟦 需求原文”标可追溯的逐字引用,“🟪 特别说明”标重要约束或例外。图标和文字一起写;单纯描述现状时不把已有内容标成新增。
20
20
  - 长解释放表外,使用局部DDL或SQL片段解释关键约束,避免在一个表格单元格里堆多段正文。
@@ -1,26 +0,0 @@
1
- (() => {
2
- window.CladoDocumentTree = function (container, documents, { selected='', query='', onOpen=()=>{}, folders=new Set() } = {}) {
3
- const needle=query.trim().toLocaleLowerCase(), root={folders:new Map(),files:[]};
4
- for(const doc of documents) {
5
- if(needle && !(doc.title+' '+doc.file).toLocaleLowerCase().includes(needle))continue;
6
- const parts=doc.file.split('/');let node=root;
7
- parts.slice(0,-1).forEach((name,i)=>{const path=parts.slice(0,i+1).join('/');if(!node.folders.has(name))node.folders.set(name,{path,folders:new Map(),files:[]});node=node.folders.get(name);});node.files.push(doc);
8
- }
9
- container.replaceChildren();
10
- function render(node, parent) {
11
- for(const [name,folder] of node.folders) {
12
- const details=document.createElement('details');details.className='tree-folder';details.open=!!needle||!folders.has('closed:'+folder.path);
13
- const summary=document.createElement('summary');summary.textContent=name;details.append(summary);
14
- details.addEventListener('toggle',()=>{if(!needle){if(details.open)folders.delete('closed:'+folder.path);else folders.add('closed:'+folder.path);}});
15
- const children=document.createElement('div');children.className='tree-children';details.append(children);render(folder,children);parent.append(details);
16
- }
17
- for(const doc of node.files) {
18
- const button=document.createElement('button');button.className='document-button';button.dataset.file=doc.file;if(doc.file===selected)button.setAttribute('aria-current','page');
19
- const strong=document.createElement('strong');strong.textContent=doc.title;
20
- const small=document.createElement('small');small.textContent=doc.file.split('/').pop();button.append(strong,small);button.onclick=()=>onOpen(doc.file);parent.append(button);
21
- }
22
- }
23
- render(root,container);
24
- if(!container.childElementCount){const empty=document.createElement('p');empty.className='tree-empty';empty.textContent=needle?'没有匹配的文档':'还没有可展示的文档';container.append(empty);}
25
- };
26
- })();