@zhama/tego-plugin-sdk 1.37.1 → 1.37.2

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.
package/dist/doctor.cjs CHANGED
@@ -1,8 +1,15 @@
1
- "use strict";var A=Object.defineProperty;var d=(e,t)=>A(e,"name",{value:t,configurable:!0});var chunkSKNPNPJP_cjs=require("./chunk-SKNPNPJP.cjs"),chunk45Y4CR4R_cjs=require("./chunk-45Y4CR4R.cjs"),chunk2P6UEAPV_cjs=require("./chunk-2P6UEAPV.cjs"),chunkN4SXZZPY_cjs=require("./chunk-N4SXZZPY.cjs"),chunk6HNG5OZI_cjs=require("./chunk-6HNG5OZI.cjs");require("./chunk-AJY7ZHXK.cjs"),require("./chunk-OP64Y4IN.cjs");var child_process=require("child_process"),promises=require("fs/promises"),path=require("path"),COLOR_ALLOW_MARKER="ui-colors-allow",PALETTE="slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose",UTILITY="bg|text|border(?:-[trblxyse])?|ring(?:-offset)?|from|via|to|fill|stroke|outline|divide|placeholder|caret|accent|decoration|shadow",COLOR_PATTERNS=[new RegExp(`(?<![\\w-])(?:${UTILITY})-(?:(?:${PALETTE})-(?:50|[1-9]00|950)|white|black)(?:\\/\\d{1,3})?(?![\\w-])`,"g"),/-\[(?:#[0-9a-fA-F]{3,8}|(?:rgba?|hsla?)\(\s*\d+)/g,/(?<![a-zA-Z0-9[-])(?:rgba?|hsla?)\(\s*\d+/g],QUOTED_HEX=/['"`]#[0-9a-fA-F]{3,8}['"`]/g,CSS_HEX=/(?<![\w&-])#[0-9a-fA-F]{3,8}(?![\w-])/g,DARK_VARIANT=/(?<![\w-])dark:(?=\S)/g,DARK_SELECTOR=/\.dark(?![\w-])/g;function stripComments(e){return e.replace(/(^|[\s{(,;])\/\*[\s\S]*?\*\//g,(t,r)=>r+t.slice(r.length).replace(/[^\n]/g," ")).replace(/(^|\s)\/\/.*$/gm,(t,r)=>r)}d(stripComments,"stripComments");function allowedLines(e){const t=new Set;return e.forEach((r,s)=>{r.includes(COLOR_ALLOW_MARKER)&&(t.add(s),/^\s*(?:\/\/|\/\*|\*|\{\/\*)/.test(r)&&t.add(s+1))}),t}d(allowedLines,"allowedLines");function findColorIssues(e,t){const r=t===".css",s=allowedLines(e.split(`
2
- `)),c=stripComments(e).split(`
3
- `),i=[...COLOR_PATTERNS,r?CSS_HEX:QUOTED_HEX],o=r?[DARK_VARIANT,DARK_SELECTOR]:[DARK_VARIANT],h=[];return c.forEach((f,n)=>{if(s.has(n))return;const u=[];for(const[a,l]of[["color",i],["dark",o]])for(const w of l)for(const k of f.matchAll(w))u.push({kind:a,match:k[0],at:k.index??0});u.sort((a,l)=>a.kind.localeCompare(l.kind)||a.at-l.at).forEach(({kind:a,match:l})=>h.push({line:n+1,kind:a,match:l}))}),h}d(findColorIssues,"findColorIssues");var rule=d((e,t,r,s)=>({id:e,severity:t,guide:r,title:s}),"rule"),DOCTOR_RULES=[rule("TP-MAN-001","error","manifest.md","tego.plugin.json is valid"),rule("TP-MAN-002","error","host-api-versions.md","hostApiRange admits every host capability the code uses"),rule("TP-PKG-001","error","manifest.md","SDK packages come from npm aliases or workspace links, never a plain @tego/* name"),rule("TP-PKG-002","warning","testing.md","package.json has the lint, type-check, test and build gates"),rule("TP-CLAW-002","warning","claw.md","Each claw skill's frontmatter name matches its folder"),rule("TP-DESK-001","error","desktop-web.md","No eval or new Function (the desktop CSP refuses them)"),rule("TP-DESK-002","error","desktop-web.md","No addresses built from location.origin (tauri://localhost on desktop)"),rule("TP-DESK-003","error","desktop-web.md","External links open with ctx.openExternal, not window.open"),rule("TP-DESK-004","error","desktop-web.md","Files are saved with ctx.download, not <a download> or a.download"),rule("TP-DESK-005","warning","desktop-web.md","No streamed responses or EventSource from the frontend (the desktop proxy buffers; use ctx.events)"),rule("TP-DESK-006","warning","desktop-web.md","Clipboard writes go through ctx.copyText"),rule("TP-WEB-001","error","desktop-web.md","The frontend calls no third-party URL (the web CSP blocks it); call the backend, which declares egress"),rule("TP-WEB-002","error","desktop-web.md","No remote or injected scripts; everything ships in the bundle"),rule("TP-UI-001","error","ui.md","Colors come from token classes: no hex, rgb(), palette classes or dark: overrides"),rule("TP-UI-002","error","ui.md","No direct @radix-ui/* imports; use @tego/ui"),rule("TP-UI-003","error","ui.md","The plugin's root element carries its scope class (.<pluginId>) when it compiles its own Tailwind"),rule("TP-UI-004","error","frontend.md","The frontend has its own error boundary"),rule("TP-I18N-001","error","i18n.md","All ten locales, with the same keys as zh-CN, and every nav label defined"),rule("TP-I18N-002","error","i18n.md","Every locale value keeps the {{placeholders}} of zh-CN and is not empty"),rule("TP-I18N-003","error","i18n.md","Every literal t('\u2026') key exists in zh-CN"),rule("TP-I18N-004","warning","i18n.md","Current terminology: \u6570\u5B57\u5458\u5DE5 / Employee, never \u6570\u5B57\u5206\u8EAB / digital avatar"),rule("TP-BE-001","error","backend.md","Identity comes from the verified ctx, never from the raw x-tego-plugin-* headers"),rule("TP-BE-002","error","access.md","No host role names in business code; ask the access engine"),rule("TP-BE-003","error","migrations.md","Migrations are <ordinal>_<name>.sql with unique ordinals"),rule("TP-BE-004","error","migrations.md","Committed migrations are never edited or deleted"),rule("TP-BE-005","warning","backend.md","Backend errors are logged through host.log, not console"),rule("TP-ACC-001","error","access.md","With an access catalog, a test asserts every route has a policy (assertRouteCoverage)"),rule("TP-ACC-002","error","access.md","With an access catalog, start() reconciles it (reconcile(host))"),rule("TP-TEST-001","warning","testing.md","The plugin has tests")],BY_ID=new Map(DOCTOR_RULES.map(e=>[e.id,e]));function doctorRule(e){return BY_ID.get(e)}d(doctorRule,"doctorRule");var VERSIONED_CAPABILITIES=[{pattern:/\.openExternal\s*\(/,since:"1.37.0",name:"ctx.openExternal"},{pattern:/\.copyText\s*\(/,since:"1.37.0",name:"ctx.copyText"},{pattern:/\b(?:ctx|host|context)\.download\s*\(/,since:"1.37.0",name:"ctx.download"},{pattern:/\b(?:ctx|host|context)\.platform\b/,since:"1.37.0",name:"ctx.platform"}],SOURCE_EXTENSIONS=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".css"]),SKIP_DIRS=new Set(["node_modules","dist","build",".tego-dev",".turbo",".drizzle","__fixtures__","coverage"]),TEST_FILE=/\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|[\\/])test[\\/]|(?:^|[\\/])test-[\w-]+\.[cm]?[jt]s$|-double\.[cm]?[jt]s$|\.d\.ts$/,IGNORE_MARKER=/tego-doctor-ignore\s+([A-Z0-9-]+(?:\s*,\s*[A-Z0-9-]+)*)/,PLACEHOLDER=/\{\{\s*([\w.-]+)\s*\}\}/g,REQUIRED_SCRIPTS=["lint","type-check","test","build"];function toPosix(e){return e.split(path.sep).join("/")}d(toPosix,"toPosix");async function walk(e,t,r){let s;try{s=await promises.readdir(path.join(e,t),{withFileTypes:!0})}catch{return}for(const c of s){const i=t?`${t}/${c.name}`:c.name;c.isDirectory()?!SKIP_DIRS.has(c.name)&&!c.name.startsWith(".")&&await walk(e,i,r):SOURCE_EXTENSIONS.has(path.extname(c.name))&&r.push(i)}}d(walk,"walk");function folderReader(e){return{async list(t){try{return(await promises.readdir(path.join(e,t),{withFileTypes:!0})).filter(s=>s.isFile()).map(s=>s.name)}catch{return[]}},readText:d(t=>promises.readFile(path.join(e,t),"utf8").catch(()=>null),"readText")}}d(folderReader,"folderReader");function runGit(e,t){return new Promise(r=>{child_process.execFile("git",["-C",e,...t],{maxBuffer:8*1024*1024},(s,c)=>r(s?null:c))})}d(runGit,"runGit");function ignoredLines(e){const t=new Map;return e.split(`
4
- `).forEach((r,s)=>{const c=IGNORE_MARKER.exec(r);if(!c?.[1])return;const i=new Set(c[1].split(",").map(h=>h.trim())),o=d(h=>t.set(h,new Set([...t.get(h)??[],...i])),"add");o(s),/^\s*(?:\/\/|\/\*|\*|\{\/\*)/.test(r)&&o(s+1)}),t}d(ignoredLines,"ignoredLines");var Findings=class{static{d(this,"Findings")}list=[];add(e,t,r={}){const{severity:s,guide:c}=doctorRule(e);this.list.push({rule:e,severity:s,message:t,guide:c,...r})}};function eachMatch(e,t,r,s){const c=ignoredLines(e.text);e.code.split(`
5
- `).forEach((i,o)=>{if(c.get(o)?.has(t))return;const h=r.exec(i);h&&s(o+1,h[0])})}d(eachMatch,"eachMatch");function partOf(e,t){const r=d(s=>!!s&&(e===s||e.startsWith(`${s}/`)),"inside");return r(t.frontend?.dir)||r(t.publicFrontend?.dir)?"frontend":r(t.backend?.dir)?"backend":r(t.claw?.dir)?"claw":r("shared")?"shared":"other"}d(partOf,"partOf");async function readJson(e){try{return JSON.parse(await promises.readFile(e,"utf8"))}catch{return}}d(readJson,"readJson");function checkPackageJson(e,t){if(!t)return;for(const c of["dependencies","devDependencies","peerDependencies"]){const i=t[c];if(!(!i||typeof i!="object"))for(const[o,h]of Object.entries(i))!o.startsWith("@tego/")||typeof h!="string"||/^(?:npm:@zhama\/tego-|workspace:|file:|link:|portal:)/.test(h)||e.add("TP-PKG-001",`${c}.${o} is "${h}": on npm @tego/* belongs to another project. Install it as "npm:@zhama/tego-${o.slice(6)}@^<sdk version>".`,{file:"package.json"})}const r=t.scripts??{},s=REQUIRED_SCRIPTS.filter(c=>typeof r[c]!="string");s.length>0&&e.add("TP-PKG-002",`package.json has no ${s.map(c=>`"${c}"`).join(", ")} script; the platform's gates are lint, type-check, test and build.`,{file:"package.json"})}d(checkPackageJson,"checkPackageJson");async function checkLocales(e,t,r,s,c){const i=s.frontend;if(!i)return;const{bundles:o,errors:h}=await chunk45Y4CR4R_cjs.verifyFrontendLocales(folderReader(t),i);for(const p of h)e.add("TP-I18N-001",p,{file:i.i18nDirPath});const f=o.get("zh-CN");if(!f)return;const n=d((p,m="",P=new Map)=>{if(typeof p!="object"||p===null||Array.isArray(p))return P.set(m,p),P;for(const[b,T]of Object.entries(p))n(T,m?`${m}.${b}`:b,P);return P},"leaves"),u=d(p=>new Set(typeof p=="string"?[...p.matchAll(PLACEHOLDER)].map(m=>m[1]):[]),"placeholders"),a=n(f);for(const[p,m]of o){const P=`${i.i18nDirPath}/${p}.json`;let b=0;for(const[T,g]of n(m)){if(b>=10)break;if(typeof g=="string"&&g.trim()===""){e.add("TP-I18N-002",`"${T}" is empty in ${p}.json.`,{file:P}),b++;continue}if(p==="zh-CN"||!a.has(T))continue;const v=u(a.get(T)),y=u(g),x=[...v].filter(E=>!y.has(E)),S=[...y].filter(E=>!v.has(E));(x.length||S.length)&&(e.add("TP-I18N-002",`"${T}" in ${p}.json has placeholders {${[...y].join(", ")}} but zh-CN has {${[...v].join(", ")}}.`,{file:P}),b++)}for(const[T,g]of n(m))if(typeof g=="string"&&/数字分身|digital avatar/i.test(g)){e.add("TP-I18N-004",`"${T}" in ${p}.json says "${/数字分身/.test(g)?"\u6570\u5B57\u5206\u8EAB":"digital avatar"}"; the platform calls them \u6570\u5B57\u5458\u5DE5 / Employee ({{avatarTerm}}).`,{file:P});break}}const l=chunk45Y4CR4R_cjs.flattenLocaleKeys(f),w=new Set(Object.keys(f)),k=d(p=>l.has(p)||["_one","_other","_zero","_few","_many","_two"].some(m=>l.has(p+m))||[...l].some(m=>m.startsWith(`${p}.`)),"exists");for(const p of c){if(p.part!=="frontend"||p.test)continue;const m=ignoredLines(p.text);p.code.split(`
6
- `).forEach((P,b)=>{if(!m.get(b)?.has("TP-I18N-003"))for(const T of P.matchAll(/\bt\(\s*['"]([A-Za-z0-9_.-]+)['"]/g)){const g=T[1],v=g.split(".")[0];!g.includes(".")||!w.has(v)||k(g)||e.add("TP-I18N-003",`t('${g}') has no entry in zh-CN.json (namespace ${chunkN4SXZZPY_cjs.pluginI18nNamespace(r.id)}).`,{file:p.path,line:b+1})}})}}d(checkLocales,"checkLocales");async function checkMigrations(e,t,r){const s=r.backend;if(!s)return;const{errors:c}=await chunk45Y4CR4R_cjs.verifyMigrationNames(folderReader(t),s.migrationsDirPath);for(const h of c)e.add("TP-BE-003",h,{file:s.migrationsDirPath});const i=await runGit(t,["diff","--name-status","HEAD","--",s.migrationsDirPath]);if(!i)return;const o=(await runGit(t,["rev-parse","--show-prefix"]))?.trim()??"";for(const h of i.split(`
7
- `)){const[f,n]=h.split(" ");if(!n||f!=="M"&&f!=="D")continue;const u=n.startsWith(o)?n.slice(o.length):n;e.add("TP-BE-004",`${u} is a committed migration and was ${f==="M"?"edited":"deleted"}; an install may have applied it already. Revert it and add a new migration instead.`,{file:u})}}d(checkMigrations,"checkMigrations");async function checkClaw(e,t,r){const s=r.claw;if(!s)return;const c=path.join(t,s.dir,"skills");let i=[];try{i=(await promises.readdir(c,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return}for(const o of i){const h=await promises.readFile(path.join(c,o,"SKILL.md"),"utf8").catch(()=>null),f=`${s.dir}/skills/${o}/SKILL.md`,n=h?/^---[\s\S]*?^name:\s*["']?([^"'\n]+)["']?\s*$/m.exec(h)?.[1]?.trim():void 0;n!==o&&e.add("TP-CLAW-002",h?`${f} declares name "${n??"(none)"}"; it must equal the folder name "${o}".`:`${s.dir}/skills/${o} has no SKILL.md.`,{file:f})}}d(checkClaw,"checkClaw");function checkSources(e,t,r,s,c,i){const o=t.hostApiRange&&chunk6HNG5OZI_cjs.isValidHostApiRange(t.hostApiRange)?chunk6HNG5OZI_cjs.hostApiRangeMinimum(t.hostApiRange):void 0,h=d(n=>{if(!o)return!1;const[u,a,l]=o.split(".").map(Number),[w,k,p]=n.split(".").map(Number);return u!==w?u<w:a!==k?a<k:l<p},"below");for(const n of s){if(!c(n)||n.test)continue;const u=d(a=>({file:n.path,line:a}),"at");if(n.part==="frontend"){if(n.path.endsWith(".css")||n.path.endsWith(".tsx")||n.path.endsWith(".ts")){const a=ignoredLines(n.text);for(const l of findColorIssues(n.text,path.extname(n.path)))a.get(l.line-1)?.has("TP-UI-001")||e.add("TP-UI-001",l.kind==="dark"?`"${l.match}" is a hand-written dark override; tokens already carry both themes.`:`"${l.match}" is a literal color; use a token class (bg-card, text-muted-foreground, bg-primary\u2026).`,u(l.line))}eachMatch(n,"TP-DESK-001",/\beval\s*\(|\bnew\s+Function\s*\(/,a=>e.add("TP-DESK-001","eval / new Function: the desktop app's CSP (script-src 'self') refuses code compiled from strings.",u(a))),eachMatch(n,"TP-DESK-002",/\b(?:window\.|document\.)?location\.origin\b/,a=>e.add("TP-DESK-002","location.origin is tauri://localhost in the desktop app; build host addresses with ctx.hostUrl(path) and share links from ctx.publicPagesUrl.",u(a))),eachMatch(n,"TP-DESK-003",/\bwindow\.open\s*\(/,a=>e.add("TP-DESK-003","window.open does not reliably open links in the desktop app; use ctx.openExternal(url) (hostApiRange ^1.37.0), or ctx.download for a file.",u(a))),eachMatch(n,"TP-DESK-004",/\.download\s*=(?!=)|<a\b[^>]*\sdownload(?:[\s=>]|$)/,a=>e.add("TP-DESK-004","An <a download> save is not handled by the desktop app; use ctx.download({ path | blob, fileName }) (hostApiRange ^1.37.0).",u(a))),eachMatch(n,"TP-DESK-005",/\bnew\s+EventSource\s*\(|\.body\s*(?:\?\.|!\.|\.)\s*getReader\s*\(/,a=>e.add("TP-DESK-005","The desktop app buffers ctx.api responses whole (and caps them at 100 MB), so streams arrive at the end; subscribe to ctx.events for pushed updates.",u(a))),eachMatch(n,"TP-DESK-006",/\bnavigator\.clipboard\./,a=>e.add("TP-DESK-006","navigator.clipboard is not available in every shell; use ctx.copyText(text) (hostApiRange ^1.37.0).",u(a))),eachMatch(n,"TP-WEB-001",/\bfetch\s*\(\s*['"`]https?:\/\//,a=>e.add("TP-WEB-001","The web app's CSP allows connections to the platform only; call your backend through ctx.api and let it reach the service (declare it in parts.backend.egress).",u(a))),eachMatch(n,"TP-WEB-002",/\bimport\s*\(\s*['"`]https?:|createElement\(\s*['"]script['"]\s*\)|<script\b[^>]*\bsrc=/,a=>e.add("TP-WEB-002","Remote or injected scripts are refused by both shells' CSP; bundle the code.",u(a))),eachMatch(n,"TP-UI-002",/from\s+['"]@radix-ui\//,a=>e.add("TP-UI-002","Import the @tego/ui wrapper instead of @radix-ui/* (the shell shares @tego/ui; a second Radix copy breaks focus and portals).",u(a)));for(const a of VERSIONED_CAPABILITIES){if(!h(a.since))continue;const l=a.name.split(".").pop();new RegExp(`\\.${l}\\s*(?:\\)|\\?(?!\\.)|&&)`).test(n.code)||eachMatch(n,"TP-MAN-002",a.pattern,w=>e.add("TP-MAN-002",`${a.name} needs host API ${a.since}, but hostApiRange is "${t.hostApiRange}"; raise it to ^${a.since}.`,u(w)))}}n.part==="backend"&&(eachMatch(n,"TP-BE-001",/\bheaders?\s*(?:\.get)?\(\s*['"]x-tego-plugin-(?:user-id|tenant-id|roles|avatar-id|delegation)['"]|\bheaders\s*\[\s*['"]x-tego-plugin-(?:user-id|tenant-id|roles|avatar-id|delegation)['"]/i,a=>e.add("TP-BE-001","Take the caller from the verified ctx (ctx.userId, ctx.tenantId, ctx.roles) that serveBackend hands you; the raw x-tego-plugin-* headers are unverified here.",u(a))),eachMatch(n,"TP-BE-005",/\bconsole\.(?:error|warn)\s*\(/,a=>e.add("TP-BE-005","Log through host.log so the message reaches the platform's logs; console output from a plugin container is not collected.",u(a)))),n.part!=="other"&&eachMatch(n,"TP-BE-002",/\b(?:roles|roleNames)\s*\??\.\s*(?:includes|indexOf)\(\s*['"`](?:admin|owner|super_?admin|tenant_?admin|member|manager)['"`]/i,a=>e.add("TP-BE-002","Do not decide by host role names; declare permissions in the access catalog (hostRoleBindings) and ask the engine (authorize / useAccess).",u(a)))}const f=s.filter(n=>n.part==="frontend"&&!n.test);if(r.frontend&&f.length>0&&(f.some(n=>/getDerivedStateFromError|componentDidCatch|PluginErrorBoundary/.test(n.code))||e.add("TP-UI-004","No error boundary in the frontend: the shell's boundary cannot see into your React root, so a render error leaves a blank page. Wrap the root in PluginErrorBoundary (@tego/plugin-sdk/react) or your own.",{file:r.frontend.dir}),i?.includes("tegoPluginTailwind"))){const n=new RegExp(`(?:className|class)=\\{?\\s*(?:cn\\()?\\s*['"\`][^'"\`]*(?<![\\w-])${t.id.replace(/[.]/g,"\\.")}(?![\\w-])`);f.some(u=>n.test(u.code))||e.add("TP-UI-003",`tegoPluginTailwind scopes every utility under .${t.id}, but no element carries className="${t.id}": none of the plugin's own classes will apply. Put it on the root element (and on portalled content, or use tegoPluginScopeRoot).`,{file:r.frontend.dir})}}d(checkSources,"checkSources");function checkAccessAndTests(e,t,r,s){const c=s.filter(o=>o.test);if(c.length===0&&e.add("TP-TEST-001","The plugin has no *.test.ts files; backend routes and pure frontend logic need tests (createTestPluginHost for SQL)."),!t.access||!r.backend)return;c.some(o=>o.text.includes("assertRouteCoverage"))||e.add("TP-ACC-001","The manifest declares an access catalog but no test calls assertRouteCoverage(app): a route without a policy would be open to everyone who can open the plugin.",{file:r.backend.dir}),s.filter(o=>(o.part==="backend"||o.part==="shared")&&!o.test).some(o=>/\breconcile\s*\(/.test(o.code))||e.add("TP-ACC-002","The manifest declares an access catalog but start() never calls reconcile(host): built-in roles and catalog changes never reach the database.",{file:r.backend.dir})}d(checkAccessAndTests,"checkAccessAndTests");async function runDoctor(e){const t=e.root;await promises.stat(path.join(t,"tego.plugin.json")).catch(()=>{throw new Error(`No tego.plugin.json in ${t}; run doctor in the plugin folder.`)});const r=new Findings;let s;try{s=JSON.parse(await promises.readFile(path.join(t,"tego.plugin.json"),"utf8"))}catch(l){return r.add("TP-MAN-001",`tego.plugin.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`,{file:"tego.plugin.json"}),summarize(r,void 0)}const c=chunkSKNPNPJP_cjs.parseTegoPluginManifest(s);if(!c.ok||!c.manifest){for(const l of c.errors)r.add("TP-MAN-001",l,{file:"tego.plugin.json"});return summarize(r,s.id)}const i=c.manifest,o=chunk2P6UEAPV_cjs.resolvePluginParts(i),h=[];await walk(t,"",h);const f=await Promise.all(h.map(async l=>{const w=await promises.readFile(path.join(t,l),"utf8");return{path:l,part:partOf(l,o),text:w,code:stripComments(w),test:TEST_FILE.test(l)}})),n=e.files?.map(l=>toPosix(path.relative(t,path.join(t,l)))),u=d(l=>!n||n.includes(l.path),"scanned"),a=o.frontend?await promises.readFile(path.join(t,o.frontend.dir,"vite.config.ts"),"utf8").catch(()=>null):null;return checkPackageJson(r,await readJson(path.join(t,"package.json"))),await checkLocales(r,t,i,o,f.filter(u)),await checkMigrations(r,t,o),await checkClaw(r,t,o),checkSources(r,i,o,f,u,a),checkAccessAndTests(r,i,o,f),summarize(r,i.id)}d(runDoctor,"runDoctor");function summarize(e,t){const r={errors:e.list.filter(i=>i.severity==="error").length,warnings:e.list.filter(i=>i.severity==="warning").length},s=new Map(DOCTOR_RULES.map((i,o)=>[i.id,o])),c=[...e.list].sort((i,o)=>(i.severity===o.severity?0:i.severity==="error"?-1:1)||(s.get(i.rule)??0)-(s.get(o.rule)??0)||(i.file??"").localeCompare(o.file??"")||(i.line??0)-(o.line??0));return{...t?{pluginId:t}:{},findings:c,...r}}d(summarize,"summarize");var UPLOAD_BLOCKING_RULES=["TP-MAN-001","TP-I18N-001","TP-BE-003"];function formatDoctorReport(e){const t=e.findings.map(r=>{const s=r.file?`${r.file}${r.line?`:${r.line}`:""} `:"";return`${r.severity==="error"?"\u2716":"\u26A0"} ${r.rule} ${s}${r.message}`});return t.push(e.findings.length===0?"\u2705 doctor: no problems":`${e.errors} error(s), ${e.warnings} warning(s). Each rule is explained in node_modules/@tego/plugin-sdk/agent/RULES.md.`),t.join(`
8
- `)}d(formatDoctorReport,"formatDoctorReport"),exports.DOCTOR_RULES=DOCTOR_RULES,exports.UPLOAD_BLOCKING_RULES=UPLOAD_BLOCKING_RULES,exports.doctorRule=doctorRule,exports.findColorIssues=findColorIssues,exports.formatDoctorReport=formatDoctorReport,exports.runDoctor=runDoctor;
1
+ "use strict";var N=Object.defineProperty;var f=(e,t)=>N(e,"name",{value:t,configurable:!0});var chunkSKNPNPJP_cjs=require("./chunk-SKNPNPJP.cjs"),chunk45Y4CR4R_cjs=require("./chunk-45Y4CR4R.cjs"),chunk2P6UEAPV_cjs=require("./chunk-2P6UEAPV.cjs"),chunkN4SXZZPY_cjs=require("./chunk-N4SXZZPY.cjs"),chunk6HNG5OZI_cjs=require("./chunk-6HNG5OZI.cjs");require("./chunk-AJY7ZHXK.cjs"),require("./chunk-OP64Y4IN.cjs");var child_process=require("child_process"),promises=require("fs/promises"),path=require("path"),crypto=require("crypto"),COLOR_ALLOW_MARKER="ui-colors-allow",PALETTE="slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose",UTILITY="bg|text|border(?:-[trblxyse])?|ring(?:-offset)?|from|via|to|fill|stroke|outline|divide|placeholder|caret|accent|decoration|shadow",COLOR_PATTERNS=[new RegExp(`(?<![\\w-])(?:${UTILITY})-(?:(?:${PALETTE})-(?:50|[1-9]00|950)|white|black)(?:\\/\\d{1,3})?(?![\\w-])`,"g"),/-\[(?:#[0-9a-fA-F]{3,8}|(?:rgba?|hsla?)\(\s*\d+)/g,/(?<![a-zA-Z0-9[-])(?:rgba?|hsla?)\(\s*\d+/g],QUOTED_HEX=/['"`]#[0-9a-fA-F]{3,8}['"`]/g,CSS_HEX=/(?<![\w&-])#[0-9a-fA-F]{3,8}(?![\w-])/g,DARK_VARIANT=/(?<![\w-])dark:(?=\S)/g,DARK_SELECTOR=/\.dark(?![\w-])/g;function stripComments(e){return e.replace(/(^|[\s{(,;])\/\*[\s\S]*?\*\//g,(t,s)=>s+t.slice(s.length).replace(/[^\n]/g," ")).replace(/(^|\s)\/\/.*$/gm,(t,s)=>s)}f(stripComments,"stripComments");function allowedLines(e){const t=new Set;return e.forEach((s,n)=>{s.includes(COLOR_ALLOW_MARKER)&&(t.add(n),/^\s*(?:\/\/|\/\*|\*|\{\/\*)/.test(s)&&t.add(n+1))}),t}f(allowedLines,"allowedLines");function findColorIssues(e,t){const s=t===".css",n=allowedLines(e.split(`
2
+ `)),l=stripComments(e).split(`
3
+ `),r=[...COLOR_PATTERNS,s?CSS_HEX:QUOTED_HEX],a=s?[DARK_VARIANT,DARK_SELECTOR]:[DARK_VARIANT],o=[];return l.forEach((p,i)=>{if(n.has(i))return;const h=[];for(const[d,c]of[["color",r],["dark",a]])for(const u of c)for(const g of p.matchAll(u))h.push({kind:d,match:g[0],at:g.index??0});h.sort((d,c)=>d.kind.localeCompare(c.kind)||d.at-c.at).forEach(({kind:d,match:c})=>o.push({line:i+1,kind:d,match:c}))}),o}f(findColorIssues,"findColorIssues");function findingFingerprint(e,t,s){return crypto.createHash("sha1").update(`${e}\0${t??""}\0${s.replace(/\s+/g," ").trim()}`).digest("hex").slice(0,16)}f(findingFingerprint,"findingFingerprint");var rule=f((e,t,s,n)=>({id:e,severity:t,guide:s,title:n}),"rule"),DOCTOR_RULES=[rule("TP-MAN-001","error","manifest.md","tego.plugin.json is valid"),rule("TP-MAN-002","error","host-api-versions.md","hostApiRange admits every host capability the code uses"),rule("TP-PKG-001","error","manifest.md","SDK packages come from npm aliases or workspace links, never a plain @tego/* name"),rule("TP-PKG-002","warning","testing.md","package.json has the lint, type-check, test and build gates"),rule("TP-PKG-003","error","manifest.md","No imports of @tego/shared or host app code; only published packages"),rule("TP-CLAW-002","warning","claw.md","Each claw skill's frontmatter name matches its folder"),rule("TP-DESK-001","error","desktop-web.md","No eval or new Function (the desktop CSP refuses them)"),rule("TP-DESK-002","error","desktop-web.md","No addresses built from location.origin (tauri://localhost on desktop)"),rule("TP-DESK-003","error","desktop-web.md","External links open with ctx.openExternal, not window.open"),rule("TP-DESK-004","error","desktop-web.md","Files are saved with ctx.download, not <a download> or a.download"),rule("TP-DESK-005","warning","desktop-web.md","No streamed responses or EventSource from the frontend (the desktop proxy buffers; use ctx.events)"),rule("TP-DESK-006","warning","desktop-web.md","Clipboard writes go through ctx.copyText"),rule("TP-WEB-001","error","desktop-web.md","The frontend calls no third-party URL (the web CSP blocks it); call the backend, which declares egress"),rule("TP-WEB-002","error","desktop-web.md","No remote or injected scripts; everything ships in the bundle"),rule("TP-WEB-003","error","frontend.md","The frontend calls its backend through ctx.api (createApiClient), never a raw fetch of a path"),rule("TP-WEB-004","error","desktop-web.md","No cookie-based auth (document.cookie, hono/cookie); ctx.api carries the credentials"),rule("TP-UI-001","error","ui.md","Colors come from token classes: no hex, rgb(), palette classes or dark: overrides"),rule("TP-UI-002","error","ui.md","No direct @radix-ui/* imports; use @tego/ui"),rule("TP-UI-003","error","ui.md","The plugin's root element carries its scope class (.<pluginId>) when it compiles its own Tailwind"),rule("TP-UI-004","error","frontend.md","The frontend has its own error boundary"),rule("TP-UI-005","warning","ui.md","Interface copy stays within budget: explanations \u2264 24 characters, any string \u2264 40 (zh-CN)"),rule("TP-I18N-001","error","i18n.md","All ten locales, with the same keys as zh-CN, and every nav label defined"),rule("TP-I18N-002","error","i18n.md","Every locale value keeps the {{placeholders}} of zh-CN and is not empty"),rule("TP-I18N-003","error","i18n.md","Every literal t('\u2026') key exists in zh-CN"),rule("TP-I18N-004","warning","i18n.md","Current terminology: \u6570\u5B57\u5458\u5DE5 / Employee, never \u6570\u5B57\u5206\u8EAB / digital avatar"),rule("TP-I18N-005","error","i18n.md","tegoAccess.* strings are merged by pack; the plugin locales do not copy them"),rule("TP-BE-001","error","backend.md","Identity comes from the verified ctx, never from the raw x-tego-plugin-* headers"),rule("TP-BE-002","error","access.md","No host role names in business code; ask the access engine"),rule("TP-BE-003","error","migrations.md","Migrations are <ordinal>_<name>.sql with unique ordinals"),rule("TP-BE-004","error","migrations.md","Committed migrations are never edited or deleted"),rule("TP-BE-005","warning","backend.md","Backend errors are logged through host.log, not console"),rule("TP-BE-006","error","backend.md","Configuration comes from host.config, never process.env"),rule("TP-BE-007","warning","backend.md","The backend app turns every error into JSON with pluginErrorHandler"),rule("TP-ACC-001","error","access.md","With an access catalog, a test asserts every route has a policy (assertRouteCoverage)"),rule("TP-ACC-002","error","access.md","With an access catalog, start() reconciles it (reconcile(host))"),rule("TP-TEST-001","warning","testing.md","The plugin has tests"),rule("TP-TEST-002","warning","testing.md","Each test file starts with a Business Cases list"),rule("TP-TPL-001","error","agent-templates.md","A template whose content changed raises its version (existing employees only see updates by version)"),rule("TP-TPL-002","warning","agent-templates.md","usageGuide.summary is at most 30 characters and quickPrompts lists 3\u20134 prompts")],BY_ID=new Map(DOCTOR_RULES.map(e=>[e.id,e]));function doctorRule(e){return BY_ID.get(e)}f(doctorRule,"doctorRule");var GUIDE_SCOPES={"manifest.md":["tego.plugin.json","package.json"],"host-api-versions.md":["tego.plugin.json"],"desktop-web.md":["<frontend>/src/**"],"frontend.md":["<frontend>/src/**"],"ui.md":["<frontend>/src/**/*.tsx","<frontend>/src/**/*.css"],"i18n.md":["<frontend>/i18n/**"],"backend.md":["<backend>/src/**"],"storage.md":["<backend>/src/**/storage*","<backend>/src/**/upload*","<backend>/src/**/files*"],"migrations.md":["<backend>/migrations/**","<backend>/src/**/schema*.ts","<backend>/drizzle.config.ts"],"access.md":["shared/access.json","<backend>/src/access*.ts","<backend>/src/**/access/**"],"claw.md":["<claw>/**"],"testing.md":["**/*.test.ts"],"agent-templates.md":["templates/**"]};function ruleCatalog(e={}){const t=f(n=>n.replace("<frontend>",e.frontend??"frontend").replace("<backend>",e.backend??"backend").replace("<claw>",e.claw??"claw"),"resolve2"),s=GUIDE_SCOPES;return{catalogVersion:1,rules:DOCTOR_RULES.map(n=>({...n,appliesTo:(s[n.guide]??[]).map(t),enforcedBy:"doctor"})),guides:Object.entries(s).map(([n,l])=>({file:n,appliesTo:l.map(t)}))}}f(ruleCatalog,"ruleCatalog");var DEFAULT_CHECK_STEPS=["doctor","lint","type-check","test"],LOCKFILES=[["pnpm-lock.yaml","pnpm"],["package-lock.json","npm"],["yarn.lock","yarn"],["bun.lockb","bun"],["bun.lock","bun"]],MAX_DETAIL=4e3,MAX_STEP_FINDINGS=50;async function detectPackageManager(e){let t=path.resolve(e);for(;;){for(const[n,l]of LOCKFILES)if(await promises.access(path.join(t,n)).then(()=>!0,()=>!1))return l;const s=path.dirname(t);if(s===t)return"npm";t=s}}f(detectPackageManager,"detectPackageManager");function run(e,t,s,n){return new Promise(l=>{const r=child_process.spawn(e,t,{cwd:s,signal:n,shell:process.platform==="win32",env:{...process.env,FORCE_COLOR:"0",NO_COLOR:"1",CI:"1"}});let a="";r.stdout.on("data",o=>a+=String(o)),r.stderr.on("data",o=>a+=String(o)),r.on("error",o=>l({code:null,output:`${a}
4
+ ${o.message}`})),r.on("close",o=>l({code:o,output:a}))})}f(run,"run");function stripAnsi(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}f(stripAnsi,"stripAnsi");function toRelative(e,t){const s=path.isAbsolute(t)?t:path.resolve(e,t),n=path.relative(e,s);return(n.startsWith("..")?t:n).split(path.sep).join("/")}f(toRelative,"toRelative");var TS_PAREN=/^(.+?)\((\d+),\d+\):\s+error\s+(TS\d+):\s+(.*)$/,TS_COLON=/^(.+?):(\d+):\d+\s+-\s+error\s+(TS\d+):\s+(.*)$/;function parseTypeErrors(e,t){const s=[];for(const n of stripAnsi(e).split(`
5
+ `)){const l=n.trim();if(l.startsWith(">"))continue;const r=TS_PAREN.exec(l)??TS_COLON.exec(l);if(!r)continue;const a=toRelative(t,r[1]);if(s.push({source:"type-check",severity:"error",rule:r[3],file:a,line:Number(r[2]),message:r[4],fingerprint:findingFingerprint(r[3],a,r[4])}),s.length>=MAX_STEP_FINDINGS)break}return s}f(parseTypeErrors,"parseTypeErrors");function parseEslintJson(e,t){const s=e.indexOf("[{"),n=e.lastIndexOf("}]");if(s<0||n<s)return e.trim().startsWith("[]")?[]:void 0;let l;try{l=JSON.parse(e.slice(s,n+2))}catch{return}const r=[];for(const a of l){const o=toRelative(t,a.filePath);for(const p of a.messages){const i=p.ruleId??"eslint";if(r.push({source:"lint",severity:p.severity>=2?"error":"warning",rule:i,file:o,...p.line?{line:p.line}:{},message:p.message,fingerprint:findingFingerprint(i,o,p.message)}),r.length>=MAX_STEP_FINDINGS)return r}}return r}f(parseEslintJson,"parseEslintJson");function parseTestFailures(e,t){const s=[],n=new Set;for(const l of stripAnsi(e).split(`
6
+ `)){const r=/^\s*(?:FAIL|×|✗)\s+(\S+\.(?:test|spec)\.[cm]?[jt]sx?)\s*(?:>\s*(.*))?$/.exec(l);if(!r)continue;const a=toRelative(t,r[1]),o=r[2]?.trim().replace(/^$/,"a test failed")??"a test failed",p=`${a}\0${o}`;if(!n.has(p)&&(n.add(p),s.push({source:"test",severity:"error",rule:"test",file:a,message:o,fingerprint:findingFingerprint("test",a,o)}),s.length>=MAX_STEP_FINDINGS))break}return s}f(parseTestFailures,"parseTestFailures");function tail(e){const t=stripAnsi(e).trim();return t.length>MAX_DETAIL?`\u2026${t.slice(-MAX_DETAIL)}`:t}f(tail,"tail");async function runChecks(e){const t=path.resolve(e.root),s=e.steps??DEFAULT_CHECK_STEPS,l=JSON.parse(await promises.readFile(path.join(t,"package.json"),"utf8").catch(()=>"{}")).scripts??{},r=await detectPackageManager(t),a=[],o=[];for(const p of s){const i=Date.now(),h=f((g,w)=>{a.push({step:p,status:g,durationMs:Date.now()-i,...w?{detail:w}:{}})},"done");if(e.signal?.aborted)break;if(p==="doctor"){const g=await runDoctor(e.files?{root:t,files:e.files}:{root:t});for(const w of g.findings)o.push({source:"doctor",...w});h(g.errors>0?"failed":"passed");continue}const d=l[p];if(!d){h("skipped",`package.json has no "${p}" script`);continue}if(p==="lint"&&/^\s*eslint\b/.test(d)){const g=e.files?.length?e.files.filter(b=>/\.[cm]?[jt]sx?$/.test(b)):["."];if(g.length===0){h("skipped","no lintable files among the given ones");continue}const k=await run(r,[...r==="npm"?["exec","--","eslint"]:["exec","eslint"],"--format","json","--no-warn-ignored",...g],t,e.signal),m=parseEslintJson(k.output,t);if(m){o.push(...m),h(m.some(b=>b.severity==="error")?"failed":"passed");continue}if(k.code===0){h("passed");continue}o.push({source:"lint",severity:"error",rule:"lint",message:tail(k.output),fingerprint:findingFingerprint("lint",void 0,"lint failed")}),h("failed",tail(k.output));continue}const c=await run(r,["run",p],t,e.signal);if(c.code===0){h("passed");continue}const u=p==="type-check"?parseTypeErrors(c.output,t):p==="test"?parseTestFailures(c.output,t):[];o.push(...u.length>0?u:[{source:p,severity:"error",rule:p,message:tail(c.output),fingerprint:findingFingerprint(p,void 0,`${p} failed`)}]),h("failed",tail(c.output))}return{passed:!a.some(p=>p.status==="failed"),steps:a,findings:o}}f(runChecks,"runChecks");function formatCheckReport(e){const t=e.steps.map(s=>`${s.status==="passed"?"\u2713":s.status==="failed"?"\u2716":"\u2013"} ${s.step}${s.status==="skipped"&&s.detail?` (${s.detail})`:""}`);for(const s of e.findings){const n=s.file?`${s.file}${s.line?`:${s.line}`:""} `:"";t.push(` ${s.severity==="error"?"\u2716":"\u26A0"} [${s.source}] ${s.rule??""} ${n}${s.message.split(`
7
+ `)[0]}`)}return t.push(e.passed?"\u2705 check: passed":"\u2716 check: failed"),t.join(`
8
+ `)}f(formatCheckReport,"formatCheckReport");var VERSIONED_CAPABILITIES=[{pattern:/\.openExternal\s*\(/,since:"1.37.0",name:"ctx.openExternal"},{pattern:/\.copyText\s*\(/,since:"1.37.0",name:"ctx.copyText"},{pattern:/\b(?:ctx|host|context)\.download\s*\(/,since:"1.37.0",name:"ctx.download"},{pattern:/\b(?:ctx|host|context)\.platform\b/,since:"1.37.0",name:"ctx.platform"},{pattern:/\b(?:ctx|context)\.events\b/,since:"1.3.0",name:"ctx.events"},{pattern:/\bhost\.directory\b/,since:"1.5.0",name:"host.directory"},{pattern:/\b(?:ctx|context)\.ai\b/,since:"1.9.0",name:"ctx.ai"},{pattern:/\.hostUrl\s*\(/,since:"1.12.0",name:"ctx.hostUrl"},{pattern:/\.uploadPath\s*\(/,since:"1.12.0",name:"storage.uploadPath"},{pattern:/\.collapseSidebar\s*\(/,since:"1.14.0",name:"ctx.layout.collapseSidebar"},{pattern:/\.managedPath\s*\(/,since:"1.15.0",name:"storage.managedPath"},{pattern:/\bstorage\.copy\s*\(/,since:"1.19.0",name:"storage.copy"},{pattern:/\b(?:ctx|context)\.office\b/,since:"1.21.0",name:"ctx.office"},{pattern:/\bhost\.tenantId\b/,since:"1.22.0",name:"host.tenantId"},{pattern:/\bproactive\.emit\s*\(/,since:"1.26.0",name:"proactive.emit"},{pattern:/\bmail\.send\s*\(/,since:"1.29.0",name:"mail.send"},{pattern:/\battention\.request\s*\(/,since:"1.34.0",name:"attention.request"}],SOURCE_EXTENSIONS=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".css"]),SKIP_DIRS=new Set(["node_modules","dist","build",".tego-dev",".turbo",".drizzle","__fixtures__","coverage"]),TEST_FILE=/\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|[\\/])test[\\/]|(?:^|[\\/])test-[\w-]+\.[cm]?[jt]s$|-double\.[cm]?[jt]s$|\.d\.ts$/,IGNORE_MARKER=/tego-doctor-ignore\s+([A-Z0-9-]+(?:\s*,\s*[A-Z0-9-]+)*)/,PLACEHOLDER=/\{\{\s*([\w.-]+)\s*\}\}/g,REQUIRED_SCRIPTS=["lint","type-check","test","build"];function toPosix(e){return e.split(path.sep).join("/")}f(toPosix,"toPosix");async function walk(e,t,s){let n;try{n=await promises.readdir(path.join(e,t),{withFileTypes:!0})}catch{return}for(const l of n){const r=t?`${t}/${l.name}`:l.name;l.isDirectory()?!SKIP_DIRS.has(l.name)&&!l.name.startsWith(".")&&await walk(e,r,s):SOURCE_EXTENSIONS.has(path.extname(l.name))&&s.push(r)}}f(walk,"walk");function folderReader(e){return{async list(t){try{return(await promises.readdir(path.join(e,t),{withFileTypes:!0})).filter(n=>n.isFile()).map(n=>n.name)}catch{return[]}},readText:f(t=>promises.readFile(path.join(e,t),"utf8").catch(()=>null),"readText")}}f(folderReader,"folderReader");function runGit(e,t){return new Promise(s=>{child_process.execFile("git",["-C",e,...t],{maxBuffer:8*1024*1024},(n,l)=>s(n?null:l))})}f(runGit,"runGit");function ignoredLines(e){const t=new Map;return e.split(`
9
+ `).forEach((s,n)=>{const l=IGNORE_MARKER.exec(s);if(!l?.[1])return;const r=new Set(l[1].split(",").map(o=>o.trim())),a=f(o=>t.set(o,new Set([...t.get(o)??[],...r])),"add");a(n),/^\s*(?:\/\/|\/\*|\*|\{\/\*)/.test(s)&&a(n+1)}),t}f(ignoredLines,"ignoredLines");var Findings=class{static{f(this,"Findings")}list=[];add(e,t,s={}){const{severity:n,guide:l}=doctorRule(e),{evidence:r,...a}=s;this.list.push({rule:e,severity:n,message:t,guide:l,...a,fingerprint:findingFingerprint(e,a.file,r??t)})}};function eachMatch(e,t,s,n){const l=ignoredLines(e.text);e.code.split(`
10
+ `).forEach((r,a)=>{if(l.get(a)?.has(t))return;const o=s.exec(r);o&&n(a+1,o[0],r.trim())})}f(eachMatch,"eachMatch");function partOf(e,t){const s=f(n=>!!n&&(e===n||e.startsWith(`${n}/`)),"inside");return s(t.frontend?.dir)||s(t.publicFrontend?.dir)?"frontend":s(t.backend?.dir)?"backend":s(t.claw?.dir)?"claw":s("shared")?"shared":"other"}f(partOf,"partOf");async function readJson(e){try{return JSON.parse(await promises.readFile(e,"utf8"))}catch{return}}f(readJson,"readJson");function checkPackageJson(e,t){if(!t)return;for(const l of["dependencies","devDependencies","peerDependencies"]){const r=t[l];if(!(!r||typeof r!="object"))for(const[a,o]of Object.entries(r))!a.startsWith("@tego/")||typeof o!="string"||/^(?:npm:@zhama\/tego-|workspace:|file:|link:|portal:)/.test(o)||e.add("TP-PKG-001",`${l}.${a} is "${o}": on npm @tego/* belongs to another project. Install it as "npm:@zhama/tego-${a.slice(6)}@^<sdk version>".`,{file:"package.json"})}const s=t.scripts??{},n=REQUIRED_SCRIPTS.filter(l=>typeof s[l]!="string");n.length>0&&e.add("TP-PKG-002",`package.json has no ${n.map(l=>`"${l}"`).join(", ")} script; the platform's gates are lint, type-check, test and build.`,{file:"package.json"})}f(checkPackageJson,"checkPackageJson");async function checkLocales(e,t,s,n,l){const r=n.frontend;if(!r)return;const{bundles:a,errors:o}=await chunk45Y4CR4R_cjs.verifyFrontendLocales(folderReader(t),r);for(const m of o)e.add("TP-I18N-001",m,{file:r.i18nDirPath});const p=a.get("zh-CN");if(!p)return;const i=f((m,b="",P=new Map)=>{if(typeof m!="object"||m===null||Array.isArray(m))return P.set(b,m),P;for(const[v,T]of Object.entries(m))i(T,b?`${b}.${v}`:v,P);return P},"leaves"),h=f(m=>new Set(typeof m=="string"?[...m.matchAll(PLACEHOLDER)].map(b=>b[1]):[]),"placeholders"),d=i(p),c=`${r.i18nDirPath}/zh-CN.json`;[...d.keys()].some(m=>m==="tegoAccess"||m.startsWith("tegoAccess."))&&e.add("TP-I18N-005","zh-CN.json contains tegoAccess.* strings; pack merges the access UI strings, remove the copy from every locale.",{file:c,evidence:"tegoAccess"});let u=0;for(const[m,b]of d){if(typeof b!="string"||u>=10)continue;const P=m.slice(m.lastIndexOf(".")+1);if(MODEL_TEXT_KEY.test(P))continue;const v=EXPLANATION_KEY.test(P)?EXPLANATION_LIMIT:ANY_STRING_LIMIT,T=copyLength(b);T>v&&(u++,e.add("TP-UI-005",`"${m}" is ${T} characters (budget ${v}); shorten it, or move the explanation into an InfoTip.`,{file:c,evidence:m}))}for(const[m,b]of a){const P=`${r.i18nDirPath}/${m}.json`;let v=0;for(const[T,y]of i(b)){if(v>=10)break;if(typeof y=="string"&&y.trim()===""){e.add("TP-I18N-002",`"${T}" is empty in ${m}.json.`,{file:P}),v++;continue}if(m==="zh-CN"||!d.has(T))continue;const E=h(d.get(T)),x=h(y),S=[...E].filter($=>!x.has($)),A=[...x].filter($=>!E.has($));(S.length||A.length)&&(e.add("TP-I18N-002",`"${T}" in ${m}.json has placeholders {${[...x].join(", ")}} but zh-CN has {${[...E].join(", ")}}.`,{file:P}),v++)}for(const[T,y]of i(b))if(typeof y=="string"&&/数字分身|digital avatar/i.test(y)){e.add("TP-I18N-004",`"${T}" in ${m}.json says "${/数字分身/.test(y)?"\u6570\u5B57\u5206\u8EAB":"digital avatar"}"; the platform calls them \u6570\u5B57\u5458\u5DE5 / Employee ({{avatarTerm}}).`,{file:P});break}}const g=chunk45Y4CR4R_cjs.flattenLocaleKeys(p),w=new Set(Object.keys(p)),k=f(m=>g.has(m)||["_one","_other","_zero","_few","_many","_two"].some(b=>g.has(m+b))||[...g].some(b=>b.startsWith(`${m}.`)),"exists");for(const m of l){if(m.part!=="frontend"||m.test)continue;const b=ignoredLines(m.text);m.code.split(`
11
+ `).forEach((P,v)=>{if(!b.get(v)?.has("TP-I18N-003"))for(const T of P.matchAll(/\bt\(\s*['"]([A-Za-z0-9_.-]+)['"]/g)){const y=T[1],E=y.split(".")[0];!y.includes(".")||!w.has(E)||k(y)||e.add("TP-I18N-003",`t('${y}') has no entry in zh-CN.json (namespace ${chunkN4SXZZPY_cjs.pluginI18nNamespace(s.id)}).`,{file:m.path,line:v+1})}})}}f(checkLocales,"checkLocales");function copyLength(e){return[...e.replace(/\{\{[^}]*\}\}/g,"X")].length}f(copyLength,"copyLength");var EXPLANATION_KEY=/(help|hint|description|desc|subtitle|intro)$/i,MODEL_TEXT_KEY=/prompt/i,EXPLANATION_LIMIT=24,ANY_STRING_LIMIT=40;async function checkTemplates(e,t,s){const n=s.agentTemplates??[];if(n.length===0)return;const l=(await runGit(t,["rev-parse","--show-prefix"]))?.trim()??"";for(const r of n){const a=r.entry.split("/").slice(0,-1).join("/"),o=`${a}/template.config.json`,p=await readJson(path.join(t,o));if(!p)continue;const i=p.content??{},h=i.usageGuide;typeof h?.summary=="string"&&copyLength(h.summary)>30&&e.add("TP-TPL-002",`${r.key}: usageGuide.summary is ${copyLength(h.summary)} characters; the landing page shows one line, keep it within 30.`,{file:o,evidence:"summary"});const d=i.quickPrompts;Array.isArray(d)&&(d.length<3||d.length>4)&&e.add("TP-TPL-002",`${r.key}: quickPrompts has ${d.length} prompt(s); offer 3\u20134 ready-to-click prompts.`,{file:o,evidence:"quickPrompts"});const u=(await runGit(t,["status","--porcelain","--untracked-files=all","--",a])??"").split(`
12
+ `).map(k=>k.slice(3).trim()).filter(k=>k&&!k.endsWith("/template.json"));if(u.length===0)continue;const g=await runGit(t,["show",`HEAD:${l}${o}`]);if(!g)continue;let w;try{w=JSON.parse(g).version}catch{continue}w!==void 0&&w===p.version&&e.add("TP-TPL-001",`${r.key} changed (${u.length} file(s)) but its version is still ${String(p.version)}; raise version in ${o} so existing employees see the update.`,{file:o,evidence:"version"})}}f(checkTemplates,"checkTemplates");async function checkMigrations(e,t,s){const n=s.backend;if(!n)return;const{errors:l}=await chunk45Y4CR4R_cjs.verifyMigrationNames(folderReader(t),n.migrationsDirPath);for(const o of l)e.add("TP-BE-003",o,{file:n.migrationsDirPath});const r=await runGit(t,["diff","--name-status","HEAD","--",n.migrationsDirPath]);if(!r)return;const a=(await runGit(t,["rev-parse","--show-prefix"]))?.trim()??"";for(const o of r.split(`
13
+ `)){const[p,i]=o.split(" ");if(!i||p!=="M"&&p!=="D")continue;const h=i.startsWith(a)?i.slice(a.length):i;e.add("TP-BE-004",`${h} is a committed migration and was ${p==="M"?"edited":"deleted"}; an install may have applied it already. Revert it and add a new migration instead.`,{file:h})}}f(checkMigrations,"checkMigrations");async function checkClaw(e,t,s){const n=s.claw;if(!n)return;const l=path.join(t,n.dir,"skills");let r=[];try{r=(await promises.readdir(l,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{return}for(const a of r){const o=await promises.readFile(path.join(l,a,"SKILL.md"),"utf8").catch(()=>null),p=`${n.dir}/skills/${a}/SKILL.md`,i=o?/^---[\s\S]*?^name:\s*["']?([^"'\n]+)["']?\s*$/m.exec(o)?.[1]?.trim():void 0;i!==a&&e.add("TP-CLAW-002",o?`${p} declares name "${i??"(none)"}"; it must equal the folder name "${a}".`:`${n.dir}/skills/${a} has no SKILL.md.`,{file:p})}}f(checkClaw,"checkClaw");function checkSources(e,t,s,n,l,r){const a=t.hostApiRange&&chunk6HNG5OZI_cjs.isValidHostApiRange(t.hostApiRange)?chunk6HNG5OZI_cjs.hostApiRangeMinimum(t.hostApiRange):void 0,o=f(i=>{if(!a)return!1;const[h,d,c]=a.split(".").map(Number),[u,g,w]=i.split(".").map(Number);return h!==u?h<u:d!==g?d<g:c<w},"below");for(const i of n){if(!l(i)||i.test)continue;const h=f((d,c)=>({file:i.path,line:d,evidence:c}),"at");if(i.part==="frontend"){if(i.path.endsWith(".css")||i.path.endsWith(".tsx")||i.path.endsWith(".ts")){const d=ignoredLines(i.text);for(const c of findColorIssues(i.text,path.extname(i.path)))d.get(c.line-1)?.has("TP-UI-001")||e.add("TP-UI-001",c.kind==="dark"?`"${c.match}" is a hand-written dark override; tokens already carry both themes.`:`"${c.match}" is a literal color; use a token class (bg-card, text-muted-foreground, bg-primary\u2026).`,h(c.line,c.match))}eachMatch(i,"TP-DESK-001",/\beval\s*\(|\bnew\s+Function\s*\(/,(d,c,u)=>e.add("TP-DESK-001","eval / new Function: the desktop app's CSP (script-src 'self') refuses code compiled from strings.",h(d,u))),eachMatch(i,"TP-DESK-002",/\b(?:window\.|document\.)?location\.origin\b/,(d,c,u)=>e.add("TP-DESK-002","location.origin is tauri://localhost in the desktop app; build host addresses with ctx.hostUrl(path) and share links from ctx.publicPagesUrl.",h(d,u))),eachMatch(i,"TP-DESK-003",/\bwindow\.open\s*\(/,(d,c,u)=>e.add("TP-DESK-003","window.open does not reliably open links in the desktop app; use ctx.openExternal(url) (hostApiRange ^1.37.0), or ctx.download for a file.",h(d,u))),eachMatch(i,"TP-DESK-004",/\.download\s*=(?!=)|<a\b[^>]*\sdownload(?:[\s=>]|$)/,(d,c,u)=>e.add("TP-DESK-004","An <a download> save is not handled by the desktop app; use ctx.download({ path | blob, fileName }) (hostApiRange ^1.37.0).",h(d,u))),eachMatch(i,"TP-DESK-005",/\bnew\s+EventSource\s*\(|\.body\s*(?:\?\.|!\.|\.)\s*getReader\s*\(/,(d,c,u)=>e.add("TP-DESK-005","The desktop app buffers ctx.api responses whole (and caps them at 100 MB), so streams arrive at the end; subscribe to ctx.events for pushed updates.",h(d,u))),eachMatch(i,"TP-DESK-006",/\bnavigator\.clipboard\./,(d,c,u)=>e.add("TP-DESK-006","navigator.clipboard is not available in every shell; use ctx.copyText(text) (hostApiRange ^1.37.0).",h(d,u))),eachMatch(i,"TP-WEB-001",/\bfetch\s*\(\s*['"`]https?:\/\//,(d,c,u)=>e.add("TP-WEB-001","The web app's CSP allows connections to the platform only; call your backend through ctx.api and let it reach the service (declare it in parts.backend.egress).",h(d,u))),eachMatch(i,"TP-WEB-002",/\bimport\s*\(\s*['"`]https?:|createElement\(\s*['"]script['"]\s*\)|<script\b[^>]*\bsrc=/,(d,c,u)=>e.add("TP-WEB-002","Remote or injected scripts are refused by both shells' CSP; bundle the code.",h(d,u))),eachMatch(i,"TP-UI-002",/from\s+['"]@radix-ui\//,(d,c,u)=>e.add("TP-UI-002","Import the @tego/ui wrapper instead of @radix-ui/* (the shell shares @tego/ui; a second Radix copy breaks focus and portals).",h(d,u))),eachMatch(i,"TP-WEB-003",/\bfetch\s*\(\s*['"`](?!https?:|data:|blob:)/,(d,c,u)=>e.add("TP-WEB-003","Call your backend through ctx.api (createApiClient from @tego/plugin-sdk/react): a raw fetch misses the base path and the credentials in the desktop app, and loses the error body.",h(d,u))),eachMatch(i,"TP-WEB-004",/\bdocument\.cookie\b/,(d,c,u)=>e.add("TP-WEB-004","Cookies do not carry the session in the desktop app; ctx.api sends the credentials in both shells.",h(d,u)))}if(i.part==="backend"&&(eachMatch(i,"TP-BE-001",/\bheaders?\s*(?:\.get)?\(\s*['"]x-tego-plugin-(?:user-id|tenant-id|roles|avatar-id|delegation)['"]|\bheaders\s*\[\s*['"]x-tego-plugin-(?:user-id|tenant-id|roles|avatar-id|delegation)['"]/i,(d,c,u)=>e.add("TP-BE-001","Take the caller from the verified ctx (ctx.userId, ctx.tenantId, ctx.roles) that serveBackend hands you; the raw x-tego-plugin-* headers are unverified here.",h(d,u))),eachMatch(i,"TP-BE-005",/\bconsole\.(?:error|warn)\s*\(/,(d,c,u)=>e.add("TP-BE-005","Log through host.log so the message reaches the platform's logs; console output from a plugin container is not collected.",h(d,u))),eachMatch(i,"TP-BE-006",/\bprocess\.env\b(?!\.NODE_ENV\b|\[\s*['"]NODE_ENV['"]\s*\])/,(d,c,u)=>e.add("TP-BE-006","Read configuration from host.config.current() (declared in the manifest's config schema); the platform does not pass a plugin its own environment variables.",h(d,u))),eachMatch(i,"TP-WEB-004",/from\s+['"]hono\/cookie['"]/,(d,c,u)=>e.add("TP-WEB-004","The caller is the verified ctx that serveBackend hands you; cookies are not how plugins authenticate.",h(d,u)))),i.part!=="other"){eachMatch(i,"TP-PKG-003",/(?:from\s+|import\s*\(\s*|require\s*\(\s*)['"](?:@tego\/shared(?:\/|['"])|@tego\/chat(?!\/plugin-surface)(?:\/|['"]))/,(c,u,g)=>e.add("TP-PKG-003","Plugins only import published packages (@tego/plugin-sdk, @tego/ui, @tego/chat/plugin-surface, \u2026); @tego/shared and host app code do not exist outside the platform.",h(c,g)));const d=ignoredLines(i.text);i.code.split(`
14
+ `).forEach((c,u)=>{if(!d.get(u)?.has("TP-PKG-003"))for(const g of c.matchAll(/(?:from\s+|import\s*\(\s*|require\s*\(\s*)['"](\.\.?\/[^'"]*)['"]/g)){const w=path.posix.normalize(path.posix.join(path.posix.dirname(i.path),g[1]));w.startsWith("../")&&e.add("TP-PKG-003",`"${g[1]}" resolves outside the plugin folder (${w}); a packed plugin only has its own files and published packages.`,h(u+1,c.trim()))}});for(const c of VERSIONED_CAPABILITIES){if(!o(c.since))continue;const u=c.name.split(".").pop();new RegExp(`\\.${u}\\s*(?:\\)|\\?(?!\\.)|&&)`).test(i.code)||eachMatch(i,"TP-MAN-002",c.pattern,(g,w,k)=>e.add("TP-MAN-002",`${c.name} needs host API ${c.since}, but hostApiRange is "${t.hostApiRange}"; raise it to ^${c.since}.`,h(g,k)))}}i.part!=="other"&&eachMatch(i,"TP-BE-002",/\b(?:roles|roleNames)\s*\??\.\s*(?:includes|indexOf)\(\s*['"`](?:admin|owner|super_?admin|tenant_?admin|member|manager)['"`]/i,(d,c,u)=>e.add("TP-BE-002","Do not decide by host role names; declare permissions in the access catalog (hostRoleBindings) and ask the engine (authorize / useAccess).",h(d,u)))}const p=n.filter(i=>i.part==="frontend"&&!i.test);if(s.frontend&&p.length>0&&(p.some(i=>/getDerivedStateFromError|componentDidCatch|PluginErrorBoundary/.test(i.code))||e.add("TP-UI-004","No error boundary in the frontend: the shell's boundary cannot see into your React root, so a render error leaves a blank page. Wrap the root in PluginErrorBoundary (@tego/plugin-sdk/react) or your own.",{file:s.frontend.dir}),r?.includes("tegoPluginTailwind"))){const i=new RegExp(`(?:className|class)=\\{?\\s*(?:cn\\()?\\s*['"\`][^'"\`]*(?<![\\w-])${t.id.replace(/[.]/g,"\\.")}(?![\\w-])`);p.some(h=>i.test(h.code))||e.add("TP-UI-003",`tegoPluginTailwind scopes every utility under .${t.id}, but no element carries className="${t.id}": none of the plugin's own classes will apply. Put it on the root element (and on portalled content, or use tegoPluginScopeRoot).`,{file:s.frontend.dir})}}f(checkSources,"checkSources");function checkAccessAndTests(e,t,s,n,l=()=>!0){const r=n.filter(o=>o.test);for(const o of r)!l(o)||!/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(o.path)||/Business Cases/.test(o.text)||e.add("TP-TEST-002",`${o.path} has no Business Cases list: start it with the cases it covers (one line each, an id per case) and begin each it() title with its id.`,{file:o.path,line:1,evidence:"no business cases"});if(s.backend){const o=n.filter(p=>p.part==="backend"&&!p.test);o.some(p=>/\bnew\s+Hono\b/.test(p.code))&&!o.some(p=>/\.onError\s*\(/.test(p.code))&&e.add("TP-BE-007","The backend app has no error handler (app.onError(pluginErrorHandler())): an uncaught error becomes Hono's plain-text 500 instead of JSON the frontend can show.",{file:s.backend.dir})}if(r.length===0&&e.add("TP-TEST-001","The plugin has no *.test.ts files; backend routes and pure frontend logic need tests (createTestPluginHost for SQL)."),!t.access||!s.backend)return;r.some(o=>o.text.includes("assertRouteCoverage"))||e.add("TP-ACC-001","The manifest declares an access catalog but no test calls assertRouteCoverage(app): a route without a policy would be open to everyone who can open the plugin.",{file:s.backend.dir}),n.filter(o=>(o.part==="backend"||o.part==="shared")&&!o.test).some(o=>/\breconcile\s*\(/.test(o.code))||e.add("TP-ACC-002","The manifest declares an access catalog but start() never calls reconcile(host): built-in roles and catalog changes never reach the database.",{file:s.backend.dir})}f(checkAccessAndTests,"checkAccessAndTests");async function runDoctor(e){const t=e.root;await promises.stat(path.join(t,"tego.plugin.json")).catch(()=>{throw new Error(`No tego.plugin.json in ${t}; run doctor in the plugin folder.`)});const s=new Findings;let n;try{n=JSON.parse(await promises.readFile(path.join(t,"tego.plugin.json"),"utf8"))}catch(c){return s.add("TP-MAN-001",`tego.plugin.json is not valid JSON: ${c instanceof Error?c.message:String(c)}`,{file:"tego.plugin.json"}),summarize(s,void 0)}const l=chunkSKNPNPJP_cjs.parseTegoPluginManifest(n);if(!l.ok||!l.manifest){for(const c of l.errors)s.add("TP-MAN-001",c,{file:"tego.plugin.json"});return summarize(s,n.id)}const r=l.manifest,a=chunk2P6UEAPV_cjs.resolvePluginParts(r),o=[];await walk(t,"",o);const p=await Promise.all(o.map(async c=>{const u=await promises.readFile(path.join(t,c),"utf8");return{path:c,part:partOf(c,a),text:u,code:stripComments(u),test:TEST_FILE.test(c)}})),i=e.files?.map(c=>toPosix(path.relative(t,path.join(t,c)))),h=f(c=>!i||i.includes(c.path),"scanned"),d=a.frontend?await promises.readFile(path.join(t,a.frontend.dir,"vite.config.ts"),"utf8").catch(()=>null):null;return checkPackageJson(s,await readJson(path.join(t,"package.json"))),await checkLocales(s,t,r,a,p.filter(h)),await checkMigrations(s,t,a),await checkClaw(s,t,a),checkSources(s,r,a,p,h,d),checkAccessAndTests(s,r,a,p,h),await checkTemplates(s,t,r),summarize(s,r.id)}f(runDoctor,"runDoctor");function summarize(e,t){const s={errors:e.list.filter(r=>r.severity==="error").length,warnings:e.list.filter(r=>r.severity==="warning").length},n=new Map(DOCTOR_RULES.map((r,a)=>[r.id,a])),l=[...e.list].sort((r,a)=>(r.severity===a.severity?0:r.severity==="error"?-1:1)||(n.get(r.rule)??0)-(n.get(a.rule)??0)||(r.file??"").localeCompare(a.file??"")||(r.line??0)-(a.line??0));return{...t?{pluginId:t}:{},findings:l,...s}}f(summarize,"summarize");var UPLOAD_BLOCKING_RULES=["TP-MAN-001","TP-I18N-001","TP-BE-003"];function formatDoctorReport(e){const t=e.findings.map(s=>{const n=s.file?`${s.file}${s.line?`:${s.line}`:""} `:"";return`${s.severity==="error"?"\u2716":"\u26A0"} ${s.rule} ${n}${s.message}`});return t.push(e.findings.length===0?"\u2705 doctor: no problems":`${e.errors} error(s), ${e.warnings} warning(s). Each rule is explained in node_modules/@tego/plugin-sdk/agent/RULES.md.`),t.join(`
15
+ `)}f(formatDoctorReport,"formatDoctorReport"),exports.DEFAULT_CHECK_STEPS=DEFAULT_CHECK_STEPS,exports.DOCTOR_RULES=DOCTOR_RULES,exports.GUIDE_SCOPES=GUIDE_SCOPES,exports.UPLOAD_BLOCKING_RULES=UPLOAD_BLOCKING_RULES,exports.detectPackageManager=detectPackageManager,exports.doctorRule=doctorRule,exports.findColorIssues=findColorIssues,exports.findingFingerprint=findingFingerprint,exports.formatCheckReport=formatCheckReport,exports.formatDoctorReport=formatDoctorReport,exports.parseEslintJson=parseEslintJson,exports.parseTestFailures=parseTestFailures,exports.parseTypeErrors=parseTypeErrors,exports.ruleCatalog=ruleCatalog,exports.runChecks=runChecks,exports.runDoctor=runDoctor;
package/dist/doctor.d.cts CHANGED
@@ -14,9 +14,52 @@ interface DoctorRule {
14
14
  /** Guide file under `agent/guides/` that explains it. */
15
15
  guide: string;
16
16
  }
17
- declare const DOCTOR_RULES: readonly [DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule];
17
+ declare const DOCTOR_RULES: readonly [DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule];
18
18
  type DoctorRuleId = (typeof DOCTOR_RULES)[number]['id'];
19
19
  declare function doctorRule(id: DoctorRuleId): DoctorRule;
20
+ /**
21
+ * Where each guide applies, as globs relative to the plugin root. `<frontend>`,
22
+ * `<backend>` and `<claw>` stand for the part directories the manifest declares
23
+ * (`frontend`, `backend`, `claw` by default). Tools use this to hand an agent
24
+ * the guide when it first touches matching files.
25
+ */
26
+ declare const GUIDE_SCOPES: {
27
+ readonly 'manifest.md': readonly ["tego.plugin.json", "package.json"];
28
+ readonly 'host-api-versions.md': readonly ["tego.plugin.json"];
29
+ readonly 'desktop-web.md': readonly ["<frontend>/src/**"];
30
+ readonly 'frontend.md': readonly ["<frontend>/src/**"];
31
+ readonly 'ui.md': readonly ["<frontend>/src/**/*.tsx", "<frontend>/src/**/*.css"];
32
+ readonly 'i18n.md': readonly ["<frontend>/i18n/**"];
33
+ readonly 'backend.md': readonly ["<backend>/src/**"];
34
+ readonly 'storage.md': readonly ["<backend>/src/**/storage*", "<backend>/src/**/upload*", "<backend>/src/**/files*"];
35
+ readonly 'migrations.md': readonly ["<backend>/migrations/**", "<backend>/src/**/schema*.ts", "<backend>/drizzle.config.ts"];
36
+ readonly 'access.md': readonly ["shared/access.json", "<backend>/src/access*.ts", "<backend>/src/**/access/**"];
37
+ readonly 'claw.md': readonly ["<claw>/**"];
38
+ readonly 'testing.md': readonly ["**/*.test.ts"];
39
+ readonly 'agent-templates.md': readonly ["templates/**"];
40
+ };
41
+ interface RuleCatalog {
42
+ /** Version of this file's shape. */
43
+ catalogVersion: 1;
44
+ rules: (DoctorRule & {
45
+ appliesTo: readonly string[];
46
+ enforcedBy: 'doctor';
47
+ })[];
48
+ guides: {
49
+ file: string;
50
+ appliesTo: readonly string[];
51
+ }[];
52
+ }
53
+ /**
54
+ * The rules as data, for tools: every doctor rule with where it applies, and
55
+ * every guide with its scope. Written to `agent/rules.json` at build time and
56
+ * printed by `tego-plugin rules --json` (with the part directories resolved).
57
+ */
58
+ declare function ruleCatalog(parts?: {
59
+ frontend?: string;
60
+ backend?: string;
61
+ claw?: string;
62
+ }): RuleCatalog;
20
63
 
21
64
  interface ColorIssue {
22
65
  line: number;
@@ -26,6 +69,54 @@ interface ColorIssue {
26
69
  /** Literal colors and hand-written dark overrides in one file; `ext` like `.tsx` or `.css`. */
27
70
  declare function findColorIssues(source: string, ext: string): ColorIssue[];
28
71
 
72
+ /** A stable id for a finding: rule, file and the offending text, never the line number. */
73
+ declare function findingFingerprint(rule: string, file: string | undefined, evidence: string): string;
74
+
75
+ type CheckStep = 'doctor' | 'lint' | 'type-check' | 'test' | 'build';
76
+ declare const DEFAULT_CHECK_STEPS: readonly CheckStep[];
77
+ interface CheckFinding {
78
+ source: CheckStep;
79
+ severity: 'error' | 'warning';
80
+ message: string;
81
+ file?: string;
82
+ line?: number;
83
+ rule?: string;
84
+ guide?: string;
85
+ fingerprint: string;
86
+ }
87
+ interface CheckStepResult {
88
+ step: CheckStep;
89
+ status: 'passed' | 'failed' | 'skipped';
90
+ durationMs: number;
91
+ /** Why it was skipped, or the end of the output when it failed. */
92
+ detail?: string;
93
+ }
94
+ interface CheckReport {
95
+ passed: boolean;
96
+ steps: CheckStepResult[];
97
+ findings: CheckFinding[];
98
+ }
99
+ interface CheckOptions {
100
+ root: string;
101
+ steps?: readonly CheckStep[];
102
+ /** Limit doctor's source checks and lint to these files (relative to root). */
103
+ files?: string[];
104
+ signal?: AbortSignal;
105
+ }
106
+ type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun';
107
+ /** The package manager of the nearest lockfile at or above `root`; npm when there is none. */
108
+ declare function detectPackageManager(root: string): Promise<PackageManager>;
109
+ /** Type errors in tsc / tsgo output (either format). */
110
+ declare function parseTypeErrors(output: string, root: string): CheckFinding[];
111
+ /** Problems in ESLint's JSON output (`--format json`). */
112
+ declare function parseEslintJson(output: string, root: string): CheckFinding[] | undefined;
113
+ /** Failed test files in vitest output (`FAIL path > suite > name`). */
114
+ declare function parseTestFailures(output: string, root: string): CheckFinding[];
115
+ /** Runs the gates in order; never throws for a failing gate. */
116
+ declare function runChecks(options: CheckOptions): Promise<CheckReport>;
117
+ /** One line per step and per finding, for the terminal. */
118
+ declare function formatCheckReport(report: CheckReport): string;
119
+
29
120
  interface DoctorFinding {
30
121
  rule: DoctorRuleId;
31
122
  severity: DoctorSeverity;
@@ -35,6 +126,12 @@ interface DoctorFinding {
35
126
  line?: number;
36
127
  /** `agent/guides/<file>` in the installed SDK. */
37
128
  guide: string;
129
+ /**
130
+ * Identifies the problem independently of its line number (rule, file and
131
+ * the offending text), so tools can tell a problem a change introduced from
132
+ * one that was already there.
133
+ */
134
+ fingerprint: string;
38
135
  }
39
136
  interface DoctorReport {
40
137
  pluginId?: string;
@@ -59,4 +156,4 @@ declare const UPLOAD_BLOCKING_RULES: readonly DoctorRuleId[];
59
156
  /** Human-readable report, one finding per line, for the terminal. */
60
157
  declare function formatDoctorReport(report: DoctorReport): string;
61
158
 
62
- export { DOCTOR_RULES, type DoctorFinding, type DoctorOptions, type DoctorReport, type DoctorRule, type DoctorRuleId, UPLOAD_BLOCKING_RULES, doctorRule, findColorIssues, formatDoctorReport, runDoctor };
159
+ export { type CheckFinding, type CheckOptions, type CheckReport, type CheckStep, type CheckStepResult, DEFAULT_CHECK_STEPS, DOCTOR_RULES, type DoctorFinding, type DoctorOptions, type DoctorReport, type DoctorRule, type DoctorRuleId, GUIDE_SCOPES, type RuleCatalog, UPLOAD_BLOCKING_RULES, detectPackageManager, doctorRule, findColorIssues, findingFingerprint, formatCheckReport, formatDoctorReport, parseEslintJson, parseTestFailures, parseTypeErrors, ruleCatalog, runChecks, runDoctor };
package/dist/doctor.d.ts CHANGED
@@ -14,9 +14,52 @@ interface DoctorRule {
14
14
  /** Guide file under `agent/guides/` that explains it. */
15
15
  guide: string;
16
16
  }
17
- declare const DOCTOR_RULES: readonly [DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule];
17
+ declare const DOCTOR_RULES: readonly [DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule, DoctorRule];
18
18
  type DoctorRuleId = (typeof DOCTOR_RULES)[number]['id'];
19
19
  declare function doctorRule(id: DoctorRuleId): DoctorRule;
20
+ /**
21
+ * Where each guide applies, as globs relative to the plugin root. `<frontend>`,
22
+ * `<backend>` and `<claw>` stand for the part directories the manifest declares
23
+ * (`frontend`, `backend`, `claw` by default). Tools use this to hand an agent
24
+ * the guide when it first touches matching files.
25
+ */
26
+ declare const GUIDE_SCOPES: {
27
+ readonly 'manifest.md': readonly ["tego.plugin.json", "package.json"];
28
+ readonly 'host-api-versions.md': readonly ["tego.plugin.json"];
29
+ readonly 'desktop-web.md': readonly ["<frontend>/src/**"];
30
+ readonly 'frontend.md': readonly ["<frontend>/src/**"];
31
+ readonly 'ui.md': readonly ["<frontend>/src/**/*.tsx", "<frontend>/src/**/*.css"];
32
+ readonly 'i18n.md': readonly ["<frontend>/i18n/**"];
33
+ readonly 'backend.md': readonly ["<backend>/src/**"];
34
+ readonly 'storage.md': readonly ["<backend>/src/**/storage*", "<backend>/src/**/upload*", "<backend>/src/**/files*"];
35
+ readonly 'migrations.md': readonly ["<backend>/migrations/**", "<backend>/src/**/schema*.ts", "<backend>/drizzle.config.ts"];
36
+ readonly 'access.md': readonly ["shared/access.json", "<backend>/src/access*.ts", "<backend>/src/**/access/**"];
37
+ readonly 'claw.md': readonly ["<claw>/**"];
38
+ readonly 'testing.md': readonly ["**/*.test.ts"];
39
+ readonly 'agent-templates.md': readonly ["templates/**"];
40
+ };
41
+ interface RuleCatalog {
42
+ /** Version of this file's shape. */
43
+ catalogVersion: 1;
44
+ rules: (DoctorRule & {
45
+ appliesTo: readonly string[];
46
+ enforcedBy: 'doctor';
47
+ })[];
48
+ guides: {
49
+ file: string;
50
+ appliesTo: readonly string[];
51
+ }[];
52
+ }
53
+ /**
54
+ * The rules as data, for tools: every doctor rule with where it applies, and
55
+ * every guide with its scope. Written to `agent/rules.json` at build time and
56
+ * printed by `tego-plugin rules --json` (with the part directories resolved).
57
+ */
58
+ declare function ruleCatalog(parts?: {
59
+ frontend?: string;
60
+ backend?: string;
61
+ claw?: string;
62
+ }): RuleCatalog;
20
63
 
21
64
  interface ColorIssue {
22
65
  line: number;
@@ -26,6 +69,54 @@ interface ColorIssue {
26
69
  /** Literal colors and hand-written dark overrides in one file; `ext` like `.tsx` or `.css`. */
27
70
  declare function findColorIssues(source: string, ext: string): ColorIssue[];
28
71
 
72
+ /** A stable id for a finding: rule, file and the offending text, never the line number. */
73
+ declare function findingFingerprint(rule: string, file: string | undefined, evidence: string): string;
74
+
75
+ type CheckStep = 'doctor' | 'lint' | 'type-check' | 'test' | 'build';
76
+ declare const DEFAULT_CHECK_STEPS: readonly CheckStep[];
77
+ interface CheckFinding {
78
+ source: CheckStep;
79
+ severity: 'error' | 'warning';
80
+ message: string;
81
+ file?: string;
82
+ line?: number;
83
+ rule?: string;
84
+ guide?: string;
85
+ fingerprint: string;
86
+ }
87
+ interface CheckStepResult {
88
+ step: CheckStep;
89
+ status: 'passed' | 'failed' | 'skipped';
90
+ durationMs: number;
91
+ /** Why it was skipped, or the end of the output when it failed. */
92
+ detail?: string;
93
+ }
94
+ interface CheckReport {
95
+ passed: boolean;
96
+ steps: CheckStepResult[];
97
+ findings: CheckFinding[];
98
+ }
99
+ interface CheckOptions {
100
+ root: string;
101
+ steps?: readonly CheckStep[];
102
+ /** Limit doctor's source checks and lint to these files (relative to root). */
103
+ files?: string[];
104
+ signal?: AbortSignal;
105
+ }
106
+ type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun';
107
+ /** The package manager of the nearest lockfile at or above `root`; npm when there is none. */
108
+ declare function detectPackageManager(root: string): Promise<PackageManager>;
109
+ /** Type errors in tsc / tsgo output (either format). */
110
+ declare function parseTypeErrors(output: string, root: string): CheckFinding[];
111
+ /** Problems in ESLint's JSON output (`--format json`). */
112
+ declare function parseEslintJson(output: string, root: string): CheckFinding[] | undefined;
113
+ /** Failed test files in vitest output (`FAIL path > suite > name`). */
114
+ declare function parseTestFailures(output: string, root: string): CheckFinding[];
115
+ /** Runs the gates in order; never throws for a failing gate. */
116
+ declare function runChecks(options: CheckOptions): Promise<CheckReport>;
117
+ /** One line per step and per finding, for the terminal. */
118
+ declare function formatCheckReport(report: CheckReport): string;
119
+
29
120
  interface DoctorFinding {
30
121
  rule: DoctorRuleId;
31
122
  severity: DoctorSeverity;
@@ -35,6 +126,12 @@ interface DoctorFinding {
35
126
  line?: number;
36
127
  /** `agent/guides/<file>` in the installed SDK. */
37
128
  guide: string;
129
+ /**
130
+ * Identifies the problem independently of its line number (rule, file and
131
+ * the offending text), so tools can tell a problem a change introduced from
132
+ * one that was already there.
133
+ */
134
+ fingerprint: string;
38
135
  }
39
136
  interface DoctorReport {
40
137
  pluginId?: string;
@@ -59,4 +156,4 @@ declare const UPLOAD_BLOCKING_RULES: readonly DoctorRuleId[];
59
156
  /** Human-readable report, one finding per line, for the terminal. */
60
157
  declare function formatDoctorReport(report: DoctorReport): string;
61
158
 
62
- export { DOCTOR_RULES, type DoctorFinding, type DoctorOptions, type DoctorReport, type DoctorRule, type DoctorRuleId, UPLOAD_BLOCKING_RULES, doctorRule, findColorIssues, formatDoctorReport, runDoctor };
159
+ export { type CheckFinding, type CheckOptions, type CheckReport, type CheckStep, type CheckStepResult, DEFAULT_CHECK_STEPS, DOCTOR_RULES, type DoctorFinding, type DoctorOptions, type DoctorReport, type DoctorRule, type DoctorRuleId, GUIDE_SCOPES, type RuleCatalog, UPLOAD_BLOCKING_RULES, detectPackageManager, doctorRule, findColorIssues, findingFingerprint, formatCheckReport, formatDoctorReport, parseEslintJson, parseTestFailures, parseTypeErrors, ruleCatalog, runChecks, runDoctor };