@a-company/paradigm 7.0.0 → 7.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{accept-orchestration-YO2V2WYA.js → accept-orchestration-XW44LF5Y.js} +1 -1
- package/dist/add-CBDU23S2.js +12 -0
- package/dist/{aggregate-KZICPVT3.js → aggregate-H7SB2UYT.js} +1 -1
- package/dist/ambient-OW5M5LVN.js +2 -0
- package/dist/{ambient-OX7YJ4PJ.js → ambient-TFLZFV5Y.js} +1 -1
- package/dist/ambient-VCTUHHIG.js +2 -0
- package/dist/arch-loader-YVOS3QRY.js +2 -0
- package/dist/{beacon-52EWNZPK.js → beacon-WVN264OT.js} +1 -1
- package/dist/calibrate-PHVP7RPH.js +4 -0
- package/dist/captain-CAXGHC2V.js +2 -0
- package/dist/captain-CWCLFOXV.js +2 -0
- package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
- package/dist/chunk-2KK4JQ55.js +17 -0
- package/dist/chunk-3I3TITBA.js +25 -0
- package/dist/chunk-3YM5ABNX.js +2 -0
- package/dist/{chunk-47YPID6H.js → chunk-6HYRS3PH.js} +21 -21
- package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
- package/dist/chunk-727PXENG.js +2 -0
- package/dist/chunk-A5EEY6NO.js +3 -0
- package/dist/{chunk-DLMDHS2X.js → chunk-ASBK55FU.js} +1 -1
- package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
- package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
- package/dist/chunk-ECO3LHCE.js +2 -0
- package/dist/chunk-FG3M6VVO.js +30 -0
- package/dist/chunk-FNYYQNJY.js +2 -0
- package/dist/{chunk-ROU3F2HZ.js → chunk-HSY75GRR.js} +3 -3
- package/dist/chunk-K6TLYNRQ.js +7 -0
- package/dist/chunk-K7KT6FL3.js +25 -0
- package/dist/chunk-KAUGQMXU.js +4 -0
- package/dist/chunk-M7JHVVDW.js +6 -0
- package/dist/chunk-NFN5UUJB.js +2 -0
- package/dist/chunk-NRP2KJ6I.js +33 -0
- package/dist/{chunk-WROJSWAO.js → chunk-QPQBXRXX.js} +1 -1
- package/dist/chunk-RVXQNS6K.js +30 -0
- package/dist/chunk-RZRFYGND.js +504 -0
- package/dist/chunk-UNSI6DVD.js +93 -0
- package/dist/{chunk-JCGCPAHF.js → chunk-USYV5QYU.js} +1 -1
- package/dist/chunk-VOPJ47QY.js +2 -0
- package/dist/{chunk-QBIQ2FYB.js → chunk-W3VWORQZ.js} +1 -1
- package/dist/chunk-WMTES556.js +2 -0
- package/dist/chunk-XBK244QR.js +6 -0
- package/dist/chunk-XSKIXXFW.js +504 -0
- package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
- package/dist/chunk-YYRP7FLC.js +2 -0
- package/dist/{compliance-MLG4W6S4.js → compliance-3M6COUCO.js} +3 -3
- package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
- package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
- package/dist/{diff-MC6AXLKX.js → diff-Z2YSIRC4.js} +1 -1
- package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
- package/dist/{docs-3YFNNZRV.js → docs-OWJ7EPD7.js} +1 -1
- package/dist/github-4X4MYINS.js +4 -0
- package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
- package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
- package/dist/index.js +9 -9
- package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
- package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
- package/dist/journal-loader-CNNA4EAU.js +2 -0
- package/dist/lint-Y4P3MHBV.js +26 -0
- package/dist/list-5XRLWD7K.js +12 -0
- package/dist/mcp.js +1 -1
- package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
- package/dist/{nomination-engine-AQHU2KBU.js → nomination-engine-EFXDEPZN.js} +1 -1
- package/dist/nomination-engine-YRHZZZUN.js +2 -0
- package/dist/notebook-loader-TZVIMNDJ.js +2 -0
- package/dist/{orchestrate-GMYEBA5T.js → orchestrate-C5NM5MFN.js} +1 -1
- package/dist/orchestration-EVWQWTOV.js +2 -0
- package/dist/orchestration-UP3KFUJT.js +2 -0
- package/dist/{platform-server-WIBVYHIV.js → platform-server-FXF3XFHM.js} +1 -1
- package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
- package/dist/quiz-QKIKAVL7.js +10 -0
- package/dist/registry-NEW4OJ44.js +2 -0
- package/dist/reindex-QZYOD5K4.js +2 -0
- package/dist/{reindex-XTRF23F7.js → reindex-W67B2LQP.js} +1 -1
- package/dist/remember-KZYAY77S.js +14 -0
- package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
- package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
- package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
- package/dist/{serve-SMGWGJLM.js → serve-ZT2Z54NK.js} +1 -1
- package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
- package/dist/{shift-JBCEDCGA.js → shift-UDKXCIW7.js} +3 -3
- package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
- package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
- package/dist/{spawn-PHA2SVQ3.js → spawn-I6XG57S2.js} +1 -1
- package/dist/status-45KIG32R.js +6 -0
- package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
- package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
- package/dist/symphony-KQJ6HIXB.js +53 -0
- package/dist/symphony-VDNDFK7H.js +2 -0
- package/dist/symphony-relay-ASMKPDEE.js +3 -0
- package/dist/task-KFND4HLF.js +3 -0
- package/dist/task-loader-HBZ3KRH2.js +2 -0
- package/dist/task-loader-IO4UVFUD.js +2 -0
- package/dist/task-settlement-NF7PFSNE.js +3 -0
- package/dist/task-settlement-TATNPY6L.js +3 -0
- package/dist/team-6WNNLBAO.js +2 -0
- package/dist/thread-2A7QKU72.js +41 -0
- package/dist/tools-GDWT74O6.js +2 -0
- package/dist/tools-SDWAFQMQ.js +142 -0
- package/dist/university-ui/assets/{index-B8hm_MdR.js → index-AbTjHBCf.js} +2 -2
- package/dist/university-ui/assets/{index-B8hm_MdR.js.map → index-AbTjHBCf.js.map} +1 -1
- package/dist/university-ui/index.html +1 -1
- package/dist/validate-OZTX3FYX.js +13 -0
- package/dist/validate-RIMSY3RP.js +9 -0
- package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
- package/package.json +1 -1
- package/dist/add-V6XR7DU5.js +0 -12
- package/dist/agent-loader-VGBPL3TH.js +0 -2
- package/dist/ambient-7HBJHJL2.js +0 -2
- package/dist/ambient-SST5CLEC.js +0 -35
- package/dist/captain-YUP3KVCA.js +0 -2
- package/dist/chunk-3MZ4J2LF.js +0 -2
- package/dist/chunk-6AKNXD22.js +0 -32
- package/dist/chunk-7SWEOPWF.js +0 -2
- package/dist/chunk-CVPKQ3JH.js +0 -8
- package/dist/chunk-EKNLG73M.js +0 -6
- package/dist/chunk-FRQRREJ6.js +0 -29
- package/dist/chunk-GD4F2HC6.js +0 -3
- package/dist/chunk-JIXHEBGK.js +0 -7
- package/dist/chunk-K54L6CFR.js +0 -25
- package/dist/chunk-MBPLJKE5.js +0 -3
- package/dist/chunk-QEQCPVF5.js +0 -4
- package/dist/chunk-QGZRM6ZB.js +0 -2
- package/dist/chunk-QO7YPQXC.js +0 -2
- package/dist/chunk-S4J337EQ.js +0 -504
- package/dist/chunk-V6MIKLMY.js +0 -18
- package/dist/journal-loader-GLH7XFTK.js +0 -2
- package/dist/lint-IGKE6UPS.js +0 -26
- package/dist/list-NC3QGT75.js +0 -12
- package/dist/lore-loader-D2ISOASW.js +0 -2
- package/dist/notebook-loader-6DYFMNJ2.js +0 -2
- package/dist/orchestration-G5MAY6IA.js +0 -2
- package/dist/quiz-TNV6APBM.js +0 -10
- package/dist/remember-MJRNTXYS.js +0 -14
- package/dist/session-work-log-QXPAXY5K.js +0 -2
- package/dist/status-ENAI35NL.js +0 -6
- package/dist/symphony-7INZR43F.js +0 -53
- package/dist/symphony-G6IENE4K.js +0 -2
- package/dist/symphony-relay-2RHG25Z4.js +0 -3
- package/dist/task-loader-IGQQ6ZFL.js +0 -2
- package/dist/task-settlement-NW4XMJGJ.js +0 -3
- package/dist/team-J2YXPEGX.js +0 -2
- package/dist/thread-HFXK65D4.js +0 -41
- package/dist/tools-HNJ7D5IO.js +0 -2
- package/dist/validate-IQG7DBFC.js +0 -9
- package/dist/validate-LSCDOLBO.js +0 -13
package/dist/chunk-JIXHEBGK.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import*as A from'fs';import*as h from'js-yaml';import {z as z$1}from'zod';import*as l from'path';import {glob}from'glob';var w=z$1.object({description:z$1.string(),type:z$1.string().optional(),parent:z$1.string().optional(),anchors:z$1.array(z$1.string()).optional(),tags:z$1.array(z$1.string()).optional(),endpoints:z$1.array(z$1.string()).optional(),tests:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),aspects:z$1.array(z$1.string()).optional(),flows:z$1.array(z$1.string()).optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),states:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),location:z$1.string().optional(),locations:z$1.array(z$1.string()).optional(),uses:z$1.array(z$1.string()).optional(),"used-by":z$1.array(z$1.string()).optional(),"used-for":z$1.array(z$1.string()).optional(),exports:z$1.array(z$1.string()).optional(),status:z$1.string().optional(),properties:z$1.record(z$1.unknown()).optional(),handles:z$1.array(z$1.string()).optional()}).passthrough(),j=w.extend({id:z$1.string()}),P=z$1.object({description:z$1.string().optional(),category:z$1.string().optional(),severity:z$1.enum(["info","warn","error"]).optional(),emitters:z$1.array(z$1.string()).optional(),related:z$1.array(z$1.string()).optional(),data:z$1.record(z$1.unknown()).optional()}),E=z$1.union([P,z$1.string().transform(o=>({description:o}))]),O=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),C=z$1.union([O,z$1.string()]),F=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),k=z$1.union([F,z$1.string()]),I=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(k)}),R=z$1.object({description:z$1.string().optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),steps:z$1.array(k).optional()}),D=z$1.object({description:z$1.string().optional(),requires:z$1.array(z$1.string()).optional(),keys:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional()}),M=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),Y=z$1.object({description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),anchors:z$1.array(z$1.string()).optional(),"applies-to":z$1.array(z$1.string()).optional(),enforcement:z$1.string().optional()}),V=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),W=z$1.object({version:z$1.string().optional(),description:z$1.string().optional(),apiSpec:z$1.string().optional(),context:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),features:z$1.union([z$1.array(j),z$1.record(w)]).optional(),components:z$1.union([z$1.array(j),z$1.record(w)]).optional(),gates:z$1.record(D).optional(),states:z$1.record(M).optional(),signals:z$1.record(E).optional(),aspects:z$1.record(Y).optional(),relationships:z$1.array(C).optional(),flows:z$1.union([z$1.array(I),z$1.record(R)]).optional(),references:z$1.array(V).optional()});function T(o){let e=z(o);return {data:e.data,errors:e.errors}}function z(o){let e=[],c=[],n;try{n=A.readFileSync(o,"utf8");}catch(r){let p=`Cannot read file: ${r.message}`;return e.push(p),c.push({message:p,type:"file"}),{data:null,errors:e,detailedErrors:c,rawContent:void 0,isYamlValid:false}}let a=n.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),s=null;try{s=h.load(a);}catch(r){let p=r,f=p.mark?.line?p.mark.line+1:void 0,u=`YAML syntax error: ${p.reason||r.message}`;return e.push(`${u}${f?` (line ${f})`:""}`),c.push({message:u,line:f,type:"yaml"}),{data:null,errors:e,detailedErrors:c,rawContent:n,isYamlValid:false}}if(s==null)return {data:{},errors:[],detailedErrors:[],rawContent:n,isYamlValid:true};if(typeof s=="object"&&s!==null){let r=s,p={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let f of Object.keys(r)){let u=f[0],g=p[u];if(!g||f.length<2)continue;let b=f.slice(1),m=r[f];if(typeof m!="object"||m===null)continue;let y=r[g]||{};g in r||(r[g]=y),b in y||(y[b]=m),delete r[f];}}let i=W.safeParse(s);if(!i.success){for(let r of i.error.issues){let p=r.path.join("."),f=r.message;e.push(`Schema error at ${p||"/"}: ${f}`),c.push({message:f,path:p||"/",type:"schema"});}return {data:s,errors:e,detailedErrors:c,rawContent:n,isYamlValid:true}}return {data:i.data,errors:[],detailedErrors:[],rawContent:n,isYamlValid:true}}function L(o){return h.dump(o,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function H(){return L({version:"1.0.0",description:"Project purpose and context",context:["Add contextual notes for AI agents here"],features:{},components:{}})}function d(o){return o?Array.isArray(o)?o.map(e=>[e.id,e]):Object.entries(o):[]}function N(o){let e={description:"",context:[],rules:{},features:{},components:{},referencedItems:{},ruleConflicts:[]};if(!o||o.length===0)return e;o.forEach(({data:n})=>{let a=new Set(e.context);for(let r of n.context||[])a.has(r)||(e.context.push(r),a.add(r));if(n.rules)for(let[r,p]of Object.entries(n.rules))e.rules[r]!==void 0&&e.rules[r]!==p&&e.ruleConflicts.push(`Conflict on rule "${r}": existing value "${e.rules[r]}" overwritten with "${p}"`),e.rules[r]=p;let s=d(n.features);for(let[r,p]of s)e.features[r]=p;let i=d(n.components);for(let[r,p]of i)e.components[r]=p;});let c=o[o.length-1];return e.description=c.data.description||e.description,e.apiSpec=c.data.apiSpec||e.apiSpec,e}async function Z(o){let e=l.resolve(o);return (await glob("**/.purpose",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((n,a)=>{let s=n.split(l.sep).length,i=a.split(l.sep).length;return s-i})}async function U(o){let e=await Z(o),c=[];for(let n of e){let{data:a,errors:s}=T(n);a&&(c.push({filePath:n,data:a}),s.length>0&&console.warn(`Warnings parsing ${n}:`,s));}return c}function J(o){let e=new Map;for(let{filePath:c,data:n}of o){let a=d(n.features);for(let[s,i]of a)e.set(s,{item:i,filePath:c});}return e}function Q(o){let e=new Map;for(let{filePath:c,data:n}of o){let a=d(n.components);for(let[s,i]of a)e.set(s,{item:i,filePath:c});}return e}function X(o){let e=new Map;for(let{filePath:c,data:n}of o)if(n.gates)for(let[a,s]of Object.entries(n.gates))e.set(a,{item:s,filePath:c});return e}function tt(o){let e=new Map;for(let{filePath:c,data:n}of o)if(n.states)for(let[a,s]of Object.entries(n.states))e.set(a,{item:s,filePath:c});return e}function et(o){let e=new Map;for(let{filePath:c,data:n}of o)if(n.flows)if(Array.isArray(n.flows))for(let a of n.flows)e.set(a.name,{item:{id:a.name,description:a.description,steps:a.steps},filePath:c});else for(let[a,s]of Object.entries(n.flows))e.set(a,{item:{id:a,description:s.description,gates:s.gates,signals:s.signals,components:s.components,steps:s.steps},filePath:c});return e}function ot(o){let e=new Map;for(let{filePath:c,data:n}of o)if(n.signals)for(let[a,s]of Object.entries(n.signals))e.set(a,{item:s,filePath:c});return e}function st(o){let e=new Map;for(let{filePath:c,data:n}of o)if(n.aspects)for(let[a,s]of Object.entries(n.aspects))e.set(a,{item:s,filePath:c});return e}function nt(o){let e=[],c=new Set;for(let{filePath:n,data:a}of o){let s=d(a.features);for(let[r,p]of s)v(`#${r}`,p,n,e,c);let i=d(a.components);for(let[r,p]of i)v(`#${r}`,p,n,e,c);}return e}function v(o,e,c,n,a){if(e.flows)for(let s of e.flows){let i=s.startsWith("$")?s:`$${s}`;a.has(i)||(a.add(i),n.push({symbol:i,type:"flow",sourceSymbol:o,filePath:c}));}if(e.gates)for(let s of e.gates){let i=s.startsWith("^")?s:`^${s}`;a.has(i)||(a.add(i),n.push({symbol:i,type:"gate",sourceSymbol:o,filePath:c}));}if(e.signals)for(let s of e.signals){let i=s.startsWith("!")?s:`!${s}`;a.has(i)||(a.add(i),n.push({symbol:i,type:"signal",sourceSymbol:o,filePath:c}));}if(e.states)for(let s of e.states){let i=s.startsWith("#")?s:s.startsWith("%")?`#${s.slice(1)}`:`#${s}`;a.has(i)||(a.add(i),n.push({symbol:i,type:"component",sourceSymbol:o,filePath:c}));}if(e.components)for(let s of e.components){let i=s.startsWith("#")?s:`#${s}`;a.has(i)||(a.add(i),n.push({symbol:i,type:"component",sourceSymbol:o,filePath:c}));}if(e.aspects)for(let s of e.aspects){let i=s.startsWith("~")?s:`~${s}`;a.has(i)||(a.add(i),n.push({symbol:i,type:"aspect",sourceSymbol:o,filePath:c}));}if(e.description){let s=_(e.description);for(let{symbol:i,type:r}of s)a.has(i)||(a.add(i),n.push({symbol:i,type:r,sourceSymbol:o,filePath:c}));}}var B=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function _(o){let e=[],c=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,n;for(;(n=c.exec(o))!==null;){let a=n[1],s=n[2],i,r;switch(a){case "#":r="component",i=`#${s}`;break;case "$":r="flow",i=`$${s}`;break;case "^":r="gate",i=`^${s}`;break;case "!":r="signal",i=`!${s}`;break;case "~":r="aspect",i=`~${s}`;break;case "%":r="component",i=`#${s}`;break;default:continue}B.has(i)||e.push({symbol:i,type:r});}return e}function S(o){return o?Array.isArray(o)?o.map(e=>[e.id,e]):Object.entries(o):[]}function $(o){return o?Array.isArray(o)?o.map(e=>e.id):Object.keys(o):[]}function rt(o,e){let c=[],n=e?`${e}: `:"",a=S(o.features);for(let[i,r]of a)x(i,r,"feature",n,c);let s=S(o.components);for(let[i,r]of s)x(i,r,"component",n,c);if(o.relationships){let i=new Set([...$(o.features),...$(o.components)]);for(let r of o.relationships){if(typeof r=="string"||!r||!r.from||!r.to)continue;let p=r.from.replace(/^[@#$%~^!?]/,"");!i.has(p)&&!r.from.includes(".")&&c.push({type:"warning",message:`${n}Relationship references unknown source: "${r.from}"`,path:"relationships"});let f=r.to.replace(/^[@#$%~^!?]/,"");!i.has(f)&&!r.to.includes(".")&&c.push({type:"warning",message:`${n}Relationship references unknown target: "${r.to}"`,path:"relationships"});}}if(o.flows){let i=new Set($(o.components));if(Array.isArray(o.flows)){for(let r of o.flows)if(!(!r||typeof r!="object")&&(r.name||c.push({type:"error",message:`${n}Flow missing required "name" field`,path:"flows"}),r.steps&&Array.isArray(r.steps)))for(let p of r.steps){if(typeof p=="string"||!p||!p.component)continue;let f=p.component.replace(/^#/,"");i.has(f)||c.push({type:"warning",message:`${n}Flow "${r.name}" references unknown component: "${p.component}"`,path:`flows.${r.name}`});}}else for(let[r,p]of Object.entries(o.flows))if(!(!p||typeof p!="object")&&p.steps&&Array.isArray(p.steps))for(let f of p.steps){if(typeof f=="string"||!f||!f.component)continue;let u=f.component.replace(/^#/,"");i.has(u)||c.push({type:"warning",message:`${n}Flow "${r}" references unknown component: "${f.component}"`,path:`flows.${r}`});}}return {valid:c.filter(i=>i.type==="error").length===0,issues:c}}function x(o,e,c,n,a){let s=`${c}s.${o}`;if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(o)||a.push({type:"warning",message:`${n}${c} ID "${o}" should use alphanumeric characters and hyphens`,path:s}),(!e.description||e.description.trim()==="")&&a.push({type:"warning",message:`${n}${c} "${o}" has no description`,path:s}),e.endpoints)for(let i of e.endpoints)/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\//.test(i)||a.push({type:"warning",message:`${n}Endpoint "${i}" in ${c} "${o}" may not be in standard format (e.g., "GET /api/users")`,path:`${s}.endpoints`});}function at(o){if(o.valid&&o.issues.length===0)return "\u2705 Purpose file is valid";let e=[],c=o.issues.filter(a=>a.type==="error"),n=o.issues.filter(a=>a.type==="warning");if(c.length>0){e.push(`
|
|
3
|
-
\u274C ${c.length} error(s):`);for(let a of c)e.push(` \u2022 ${a.message}${a.path?` (${a.path})`:""}`);}if(n.length>0){e.push(`
|
|
4
|
-
\u26A0\uFE0F ${n.length} warning(s):`);for(let a of n)e.push(` \u2022 ${a.message}${a.path?` (${a.path})`:""}`);}return o.valid?e.push(`
|
|
5
|
-
\u2705 Purpose file is valid (with warnings)`):e.push(`
|
|
6
|
-
\u274C Purpose file is invalid`),e.join(`
|
|
7
|
-
`)}export{z as a,L as b,H as c,N as d,Z as e,U as f,J as g,Q as h,X as i,tt as j,et as k,ot as l,st as m,nt as n,rt as o,at as p};
|
package/dist/chunk-K54L6CFR.js
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a,O,l as l$1,D as D$1,G as G$1,L,F,K,J,I as I$1,N}from'./chunk-QBIQ2FYB.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {b as b$2}from'./chunk-RGSFU2YW.js';import {m,q,k,n,o,l,i,j as j$1,g}from'./chunk-TMDPDIWA.js';import {f}from'./chunk-KLBH26PA.js';import {j,a as a$3,i as i$1,b as b$1,h as h$1,g as g$2,c,d as d$2}from'./chunk-GRZQIKST.js';import {d,g as g$1,e,h,j as j$2,f as f$1}from'./chunk-ACJWUOMA.js';import {b,a as a$1}from'./chunk-EK4ZRIFJ.js';import*as D from'fs';import*as I from'path';import*as G from'js-yaml';import {execSync}from'child_process';import*as Ot from'os';b();b();var Tt=".paradigm/navigator.yaml";async function nt(n){let e=I.join(n,Tt);if(!D.existsSync(e))return {config:null,configPath:null};try{let o=D.readFileSync(e,"utf8");return {config:G.load(o),configPath:e}}catch(o){return a$1.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function ot(n,e,o){switch(e.intent){case "find":return Wt(n,e.target||"");case "explore":return Lt(n,e.target||"");case "context":return Ht(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Wt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let r=n.symbols[e];if(r)t.paths.push(r),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${r}`;else {let s=Object.entries(n.symbols).filter(([i])=>i.includes(e.slice(1))).slice(0,5);s.length>0?(t.paths=s.map(([,i])=>i),t.symbols=s.map(([i])=>i),t.explanation=`Found ${s.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let r=Object.entries(n.symbols).filter(([s])=>s.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(r.length>0)t.paths=r.map(([,s])=>s),t.symbols=r.map(([s])=>s),t.explanation=`Found ${r.length} symbols matching "${e}"`;else {let s=Bt(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=we(t.paths,n),t}function Lt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Ht(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=Mt(r);for(let[i,a]of Object.entries(n.structure))a&&s.some(c=>i.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[i,a]of Object.entries(n.symbols)){let c=i.slice(1).toLowerCase();s.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(i));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],r.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!r.includes("doc")&&!r.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Bt(n,e){let o=e.toLowerCase();for(let[t,r]of Object.entries(n.structure))if(r&&(t.toLowerCase().includes(o)||o.includes(t.toLowerCase())))return r;return null}function Mt(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o.length>2&&!e.has(o))}function we(n,e){let o={};for(let t of n){let r=0;e.key_files.config.some(s=>t.includes(s))&&(r+=100),e.key_files.entry.some(s=>t.includes(s))&&(r+=80),e.key_files.types.some(s=>t.includes(s))&&(r+=60),r-=t.split("/").length*2,o[t]=r;}return [...n].sort((t,r)=>(o[r]||0)-(o[t]||0))}b();function Jt(n){let e=I.resolve(n),o=D.readFileSync(e,"utf8"),t=G.load(o);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let r={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let s of t.members)if(typeof s=="object"&&s!==null){let i=s;r.members.push({name:String(i.name||""),path:String(i.path||""),role:i.role,exports:Array.isArray(i.exports)?i.exports.map(String):void 0});}}return r}function rt(n,e){let o=I.resolve(n),t=I.resolve(o,e);if(!D.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=Jt(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=I.dirname(t),i="";for(let c of r.members){let l=I.resolve(s,c.path);if(st(l)===st(o)){i=c.name;break}}if(!i)return a$1.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:r.name}),null;let a=new Map;for(let c of r.members){if(c.name===i)continue;let l=I.resolve(s,c.path),d=I.join(l,".paradigm","scan-index.json");if(!D.existsSync(d)){a$1.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let p=JSON.parse(D.readFileSync(d,"utf8")),m=Ut(p);c.exports&&c.exports.length>0&&(m=Gt(m,c.exports));let h=null,x=I.join(l,"portal.yaml");if(D.existsSync(x))try{let f=D.readFileSync(x,"utf8"),P=G.load(f);P&&(h=P);}catch{}a.set(c.name,{index:m,gateConfig:h});}catch(p){a$1.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:p.message});}}return {config:r,workspacePath:t,currentMember:i,siblingIndices:a}}function Gt(n,e){let t=q(n).filter(r=>{let s=r.symbol;return e.some(i=>qt(i,s))});return zt(t)}function qt(n,e){let o=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${o}$`,"i").test(e)}function xe(n,e){let o=[];for(let[t,r]of n.siblingIndices){let s=m(r.index,e);for(let i of s)o.push({project:t,symbol:`${t}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function it(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=q(s.index);for(let c of a){let l=c.references||[],d=c.description||"",p=l.some(h=>h===t||h===e||h.endsWith(`/${t}`)),m=d.includes(t);(p||m)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}function st(n){return I.resolve(n).replace(/\/+$/,"")}function Ut(n){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},o=[];for(let[t,r]of Object.entries(e)){let s=n[t];if(!(!s||typeof s!="object"))for(let[i,a]of Object.entries(s)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[r]||"#";o.push({id:i,symbol:a.symbol||`${c}${i}`,type:r,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return j$1({symbols:o,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function zt(n){return j$1({symbols:n.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}var Vt={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function Zn(){return [Vt]}async function lt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await nt(o.rootDir);if(r.config||(r={config:Kt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await a.getOrCompute(s,()=>{let c=ot(r.config,t,o.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let d=xe(o.workspace,t.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let d=xe(o.workspace,t.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(p=>({symbol:p.symbol,type:p.type,description:p.description,project:p.project})));}}return JSON.stringify(l,null,2)}),a$1=i;if(e.response_format==="concise")try{let c=JSON.parse(i);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a$1=JSON.stringify(c,null,2);}catch{}try{let c=I.join(o.rootDir,".paradigm",".nav-called");D.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Kt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=q(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function pt(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of i)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
|
|
3
|
-
`);for(let l of c.slice(0,t)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,p,m,h]=d,x=I.relative(n,p),f="unknown";x.includes(".purpose")||x.includes("portal.yaml")?f="purpose":h.includes("//")||h.includes("#")||h.includes("*")?f="comment":f="code",r.push({filePath:x,line:parseInt(m,10),content:h.trim().slice(0,200),context:f});}}return r}b();var Yt=30*1e3,ft=new Map;async function mt(n){let e=I.resolve(n),o=ft.get(e);if(o&&Date.now()-o.loadedAt<Yt)return o.index;let t=await Xt(e);return t&&ft.set(e,{index:t,loadedAt:Date.now()}),t}async function Xt(n){let e=I.join(n,".paradigm","flow-index.json");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return JSON.parse(o)}catch(o){return a$1.component("#flow-loader").error("Error parsing flow-index.json",{error:o}),null}}function Zt(n,e){let o=n.symbolToFlows[e]||[],t=[];for(let r of o){let s=n.flows[r];if(!s)continue;let i=s.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of i){let l=s.steps.slice(c+1).map(d=>d.id);t.push({flowId:s.id,definedIn:s.definedIn,description:s.description,trigger:s.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:s.validation});}}return t}function ut(n,e){let o=Zt(n,e),t=new Set;for(let i of o)i.validation?.command&&t.add(i.validation.command);let r="low",s=o.reduce((i,a)=>i+a.downstreamSteps.length,0);return o.length>3||s>10?r="high":(o.length>1||s>3)&&(r="medium"),{symbol:e,totalFlows:o.length,impactLevel:r,affectedFlows:o,validationCommands:Array.from(t),suggestion:o.length>0?`Changes to ${e} may affect ${o.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function mo(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function le(n$1,e,o$1){if(n$1!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:r=3,includeWorkspace:s=false,response_format:i}=e,a=k(o$1.index,t);if(!a){let w=en(o$1.rootDir,t);return O(w.length,n$1),{handled:true,text:w}}let c=Math.min(Math.max(r||3,1),5),l$2=n(o$1.index,t),d=new Set([t]),p=new Map;function m(w,v){if(v>=c)return;let u=[];for(let k of w){if(d.has(k))continue;d.add(k);let N=n(o$1.index,k);for(let T of N)d.has(T.symbol)||u.push(T.symbol);}u.length>0&&(p.set(v+1,u),m(u,v+1));}m(l$2.map(w=>w.symbol),1);let h=new Set;for(let[,w]of p)for(let v of w)v!==t&&!l$2.find(u=>u.symbol===v)&&h.add(v);let x=o(o$1.index,t),f=l$2.length+h.size,P="low";f>10?P="high":f>3&&(P="medium");let A=await mt(o$1.rootDir),R=null;if(A){let w=ut(A,t);w.totalFlows>0&&(w.impactLevel==="high"&&P==="low"?P="medium":w.impactLevel==="high"&&(P="high"),R={totalFlows:w.totalFlows,affectedFlows:w.affectedFlows.map(v=>({flowId:v.flowId,impactLevel:v.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${v.stepAffected.position}, affects ${v.downstreamSteps.length} downstream steps`})),validationSuggestion:w.validationCommands.length>0?`Run: ${w.validationCommands[0]}`:void 0});}let $=new Set([t,...l$2.map(w=>w.symbol),...h]),F=[];try{let w=l(o$1.index,"gate");for(let v of w)$.has(v.symbol)&&F.push({gate:v.symbol,description:v.description});for(let v of l$2)v.type==="gate"&&!F.find(u=>u.gate===v.symbol)&&F.push({gate:v.symbol,description:v.description});}catch{}let C={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:P,analysis:{directlyAffected:l$2.map(w=>({symbol:w.symbol,type:w.type,description:w.description})),indirectlyAffected:Array.from(h),indirectByLevel:Object.fromEntries(p),dependsOn:x.map(w=>({symbol:w.symbol,type:w.type}))},summary:{directCount:l$2.length,indirectCount:h.size,totalAffected:f,dependsOnCount:x.length,levelsAnalyzed:c},recommendation:tn(P)};R&&(C.affectedFlows=R),F.length>0&&(C.affectedGates=F),C.suggestedReviewScope=nn(P,l$2.length,h.size,F.length,R?.totalFlows??0);try{let w=await l$1(o$1.rootDir,t);w.length>0&&(C.personas_affected=w,w.length>2&&P==="low"&&(C.impact="medium"));}catch{}try{let w=D$1(o$1.rootDir,t);w.length>0&&(C.university_content_affected=w.map(v=>({id:v.id,title:v.title,type:v.type,stale:v.stale})));}catch{}if(s&&o$1.workspace){let w=it(o$1.workspace,t);if(w.length>0){C.workspaceImpact={siblings:w.map(u=>({project:u.project,references:u.references.map(k=>({symbol:k.symbol,type:k.type,description:k.description}))}))};let v=w.reduce((u,k)=>u+k.references.length,0);v>0&&P==="low"&&(C.impact="medium"),v>5&&(C.impact="high");}}let O$1=i==="concise"?{symbol:C.symbol,impact:C.impact,summary:C.summary}:C,E=JSON.stringify(O$1,null,2);return O(E.length,n$1),{handled:true,text:E}}function en(n,e){let o=pt(n,e,{maxResults:20});if(o.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(o.map(i=>i.filePath))],r={};for(let i of o)r[i.context]=(r[i.context]||0)+1;let s="low";return t.length>10||o.length>20?s="high":(t.length>3||o.length>5)&&(s="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:s,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:o.length,contextBreakdown:r,sampleReferences:o.slice(0,5).map(i=>({file:i.filePath,line:i.line,preview:i.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function tn(n){switch(n){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function nn(n,e,o,t,r){let s=[];return e>0&&s.push(`Review ${e} direct dependent(s) for breaking changes`),o>0&&s.push(`Scan ${o} indirect dependent(s) for cascading effects`),t>0&&s.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),r>0&&s.push(`Validate ${r} affected flow(s) end-to-end`),n==="high"?s.push("Consider running full test suite before merging"):n==="medium"&&s.push("Run targeted tests for affected components"),s.length===0&&s.push("No downstream dependents detected - safe to proceed"),s}b();b();var on=30*1e3,ve=new Map,yt=".paradigm/wisdom";async function ht(n){let e=I.resolve(n),o=ve.get(e);if(o&&Date.now()-o.loadedAt<on)return o.context;let t=await sn(e);return ve.set(e,{context:t,loadedAt:Date.now()}),t}async function sn(n){let e$1=I.join(n,yt),o=D.existsSync(e$1),[t,r,s,i]=o?await Promise.all([rn(e$1),an(e$1),cn(e$1),ln(e$1)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e(),l=f$1();}catch{}let d$1=new Set(r.map(f=>f.id)),p=r.map(f=>({...f,scope:"project"}));for(let f of a)d$1.has(f.id)||p.push({...f,scope:"global"});let m=new Set(i.map(f=>f.id)),h=i.map(f=>({...f,scope:"project"}));for(let f of c)m.has(f.id)||h.push({...f,scope:"global"});let x=t;if(l&&!t)x=l;else if(l&&t){let f={...t.by_symbol};if(l.by_symbol)for(let[P,A]of Object.entries(l.by_symbol))f[P]||(f[P]=A);x={...t,by_symbol:f,global:{...l.global,...t.global}};}return {preferences:x,antipatterns:p,decisions:h,expertise:s}}function z(n){let e=I.resolve(n);ve.delete(e);}async function rn(n){let e=I.join(n,"preferences.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:o}),null}}async function an(n){let e=I.join(n,"antipatterns.yaml");if(!D.existsSync(e))return [];try{let o=D.readFileSync(e,"utf8");return G.load(o).antipatterns||[]}catch(o){return a$1.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:o}),[]}}async function cn(n){let e=I.join(n,"expertise.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:o}),null}}var gt=new Set;async function ln(n){let e=I.join(n,"decisions");if(!D.existsSync(e))return [];let o=[];try{let t=D.readdirSync(e);t.some(s=>s.endsWith(".yaml")||s.endsWith(".yml"))&&!gt.has(e)&&(gt.add(e),a$1.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let s of t){if(!s.endsWith(".yaml")&&!s.endsWith(".yml"))continue;let i=I.join(e,s);try{let a=D.readFileSync(i,"utf8"),c=G.load(a);o.push(c);}catch(a){a$1.component("#wisdom-loader").error(`Error parsing ${s}`,{error:a});}}}catch(t){a$1.component("#wisdom-loader").error("Error reading decisions directory",{error:t});}return o.sort((t,r)=>t.id.localeCompare(r.id)),o}function bt(n,e){return e.map(o=>dn(n,o))}function dn(n,e){let o=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(i=>i.symbols.some(a=>a===e||de(e,a))),r=n.decisions.filter(i=>i.symbols.some(a=>a===e||de(e,a))),s=n.expertise?.experts.filter(i=>i.symbols?.some(a=>a===e||de(e,a)))||[];return {symbol:e,preferences:o,antipatterns:t,decisions:r,experts:s}}function wt(n,e){return n.expertise?n.expertise.experts.filter(o=>!!(e.symbol&&o.symbols&&o.symbols.some(t=>t===e.symbol||de(e.symbol,t))||e.area&&o.areas&&o.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function de(n,e){if(e.endsWith("*")){let o=e.slice(0,-1);return n.startsWith(o)}return n===e}async function St(n,e){let o=I.join(n,yt),t=I.join(o,"antipatterns.yaml");D.existsSync(o)||D.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(D.existsSync(t))try{let s=D.readFileSync(t,"utf8"),i=G.load(s);i&&typeof i=="object"&&(r={version:i.version||"1.0",antipatterns:Array.isArray(i.antipatterns)?i.antipatterns:[]});}catch{}r.antipatterns.push({...e,added:new Date().toISOString()}),D.writeFileSync(t,G.dump(r,{lineWidth:-1})),z(n);}b();var xt=".paradigm/history";async function vt(n){let e=I.join(n,xt);if(!D.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([pn(e),fn(e)]);return {index:o,validation:t}}async function pn(n){let e=I.join(n,"index.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing index.yaml",{error:o.message}),null}}async function fn(n){let e=I.join(n,"validation.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return G.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing validation.yaml",{error:o.message}),null}}function wo(n,e){return e.map(o=>mn(n,o))}function mn(n,e){let o=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let s of n.index.co_changes)if(s.symbols.includes(e))for(let i of s.symbols)i!==e&&!t.includes(i)&&t.push(i);}let r=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:o,recent:o?.recent||[],co_changes:t,validation:r}}function So(n,e){let o=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let i of e){let a=n.index.by_symbol?.[i];a&&(a.fragility==="high"||a.fragility==="critical")&&o.push({symbol:i,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(l=>l.symbol===i);c&&!o.find(l=>l.symbol===i)&&o.push(c);}for(let i of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(i));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==i&&!e.includes(d));l.length>0&&c.correlation>.7&&t.push(`${i} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let r=o.filter(i=>i.fragility==="critical").length===0,s=[];return o.length>0&&(s.push("Consider adding extra test coverage before modifying fragile symbols"),s.push("Review recent rollbacks and failures for these symbols")),t.length>0&&s.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:o,warnings:t,safe_to_modify:r,recommendations:s}}async function un(n,e){let o=I.join(n,xt),t=I.join(o,"log.jsonl");D.existsSync(o)||D.mkdirSync(o,{recursive:true});let r=gn(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
|
|
4
|
-
`;return D.appendFileSync(t,a),r}async function xo(n,e,o,t){return un(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function gn(n){let e=1;return D.existsSync(n)&&(e=D.readFileSync(n,"utf8").split(`
|
|
5
|
-
`).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Fo(n){let e=I.resolve(n),o=await i(e),t=j$1(o),r=null,s=I.join(e,"portal.yaml");if(D.existsSync(s))try{r=await g(s);}catch(d){let p=d?.name??"Error";a$1.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:p});}let i$1=I.basename(e),a=I.join(e,".premise");if(D.existsSync(a))try{let p=D.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);p&&(i$1=p[1].trim());}catch{}let c=null,l=I.join(e,".paradigm","config.yaml");if(D.existsSync(l))try{let d=D.readFileSync(l,"utf8"),p=G.load(d);p&&typeof p=="object"&&(p.version||a$1.component("#index-loader").warn('config.yaml missing "version" field'),p.project||a$1.component("#index-loader").warn('config.yaml missing "project" field')),p&&typeof p.workspace=="string"&&(c=rt(e,p.workspace));}catch(d){a$1.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:t,aggregation:o,gateConfig:r,projectName:i$1,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function fe(n){return n.wisdom||(n.wisdom=await ht(n.rootDir)),n.wisdom}async function Io(n){return n.history||(n.history=await vt(n.rootDir)),n.history}j();b();var _t=false;function Bo(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Pt(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await fe(o),i=bt(s,t),a={symbols:t,wisdom:i.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(p=>({id:p.id,description:p.description,reason:p.reason,alternative:p.alternative,scope:p.scope||"project"})),decisions:d.decisions.map(p=>({id:p.id,title:p.title,status:p.status,decision:p.decision,scope:p.scope||"project"})),experts:d.experts.map(p=>p.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((d,p)=>d+p.antipatterns.length,0),l=i.reduce((d,p)=>d+p.decisions.length,0);a.summary={symbols_with_preferences:i.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},p=[];for(let m of t){let h=await a$3(o.rootDir,{symbol:m,hasAssessment:!0,limit:100});if(h.length===0)continue;let x={correct:0,partial:0,incorrect:0},f=0,P=0;for(let R of h){let $=R.assessment.verdict;x[$]++,R.confidence!=null&&(f+=R.confidence,P++);}d[m]={total:h.length,...x,avgConfidence:P>0?Math.round(f/P*1e3)/1e3:null};let A=(x.correct+x.partial*.5)/h.length;A<.6&&h.length>=3&&p.push(`Low historical accuracy for ${m}: ${Math.round(A*100)}% across ${h.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),p.length>0&&(a.calibration_warnings=p);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:t,id:r,symbols:s,description:i,reason:a,alternative:c,title:l,status:d,rationale:p,consequences:m,scope:h$1="project"}=e$1;if(t==="antipattern"){if(!i||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let x={id:r,symbols:s,description:i,reason:a,alternative:c};return h$1==="global"?g$1(x):await St(o.rootDir,x),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:h$1,message:`Antipattern recorded to ${h$1} scope`})}}if(t==="decision"){if(!l||!i||!p||!m)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(_t||(_t=true,a$1.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),h$1==="global"){let P={id:r,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:p,consequences:m};return h(P),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let x=a$2(o.rootDir,{title:l,decision:i,rationale:{factors:p.factors,conclusion:p.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:d==="accepted"?"active":d==="proposed"?"proposed":"active",context:a||void 0,consequences:m,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),f=d$1(o.rootDir,x.id);return z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:x.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${x.id})`,...f?{companion_lore_id:f}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:r}=e$1,s=await fe(o),i=I.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(l=>l.id===r);return a?d().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g$1({...a,learned_from:`promoted from ${i}`}),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(l=>l.id===r);return a?e().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),z(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await fe(o),i=wt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Go(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function jt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await I$1(o.rootDir,t,r);return s.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:s.length,task:t,matches:s.map(i=>({id:i.protocol.id,name:i.protocol.name,description:i.protocol.description,score:i.score,status:i.protocol.status,exemplar:i.protocol.exemplar,last_verified:i.protocol.last_verified,steps:i.protocol.steps.map(yn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await G$1(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=L(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await J(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await K(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await G$1(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=L(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s=(await F(o.rootDir)).map(a=>{let c=L(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s.length,current:s.filter(a=>a.status==="current").length,stale:s.filter(a=>a.status==="stale").length,broken:s.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s,health:i},null,2)}}default:return {handled:false,text:""}}}function yn(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}j();var ee=null,ke=false;async function _e(n){if(ee)ke||(await ee.ensureReady(),ke=true);else {let e=I.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function hn(n,e){return (await _e(n)).recordPracticeEvent(e)}async function zo(n,e){return (await _e(n)).getPracticeEvents(e)}async function Ce(n,e){return (await _e(n)).getComplianceRate(e)}async function Rt(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await Ce(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Vo(n,e,o){let t=[];for(let r of e){let s=await hn(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function Ft(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var me={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function It(){let n=process.env.PARADIGM_AUTHOR;if(n)return Pe(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Pe(e)}catch{}try{let e=Ot.userInfo().username;if(e)return Pe(e)}catch{}return "unknown"}function Pe(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function ss(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function je(n,e,o){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(At)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:m,duration_minutes:h,decisions:x,errors_encountered:f,learnings:P,verification:A,tags:R,meta:$,body:F,linked_lore:C,linked_tasks:O,linked_commits:E,confidence:w}=e;if(t==="decision")return a$1.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:me.removed_in,successor_tool:me.successor_tool}),Ft(me);let v;try{let S=new Date(Date.now()-2592e6).toISOString(),b=await Ce(o.rootDir,{dateFrom:S});if(b.total>0){let y=(await Rt(o.rootDir,{dateFrom:S})).filter(_=>_.rate<60).map(_=>_.category);v={rate:b.rate,followed:b.followed,skipped:b.skipped,partial:b.partial,weakAreas:y.length>0?y:void 0};}}catch{}let u={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:h,author:It(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:p,commit:m,decisions:x,errors_encountered:f,learnings:P,verification:A,tags:R,meta:$||void 0,habit_compliance:v,body:F,linked_lore:C,linked_tasks:O,linked_commits:E,confidence:w!=null&&w>=0&&w<=1?w:void 0},k=await d$2(o.rootDir,u);j$2().setLastLoreEntryId(k);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:b}=await import('./agent-loader-W3RQJVW7.js');b(o.rootDir,S,{symbols_touched:i,confidence:w!=null&&w>=0&&w<=1?w:void 0});}}catch{}let N$1=null;try{c&&c.length>=2&&(N$1=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,b=S==="auto"?wn(e):S;try{if(b==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:u.agent?.model||"unknown",summary:u.summary,outcome:u.verification?.status==="pass"?"pass":u.verification?.status==="fail"?"fail":"partial",files_modified:u.files_modified,symbols_touched:u.symbols_touched,commit:u.commit,linked_lore:u.id||k}),T="work-log";}else if(b==="journal"&&u.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-GLH7XFTK.js');for(let y of u.learnings)g(u.agent?.model||"unknown",{trigger:"self_reflection",insight:y,project:o.projectName||"unknown",transferable:!1,linked_work_log:u.id||k});T="journal";}else if(b==="decision"&&u.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let y of u.decisions)g(o.rootDir,{title:y.decision.slice(0,100),decision:y.decision,rationale:y.rationale,participants:[{id:`agent/${u.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:u.symbols_touched,status:"active",linked_lore:u.id||k});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:k,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...N$1?{protocol_suggestion:N$1}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,r=await c(o.rootDir),s=await a$3(o.rootDir,{limit:t}),i={};for(let l of s)for(let d of l.symbols_touched)i[d]=(i[d]||0)+1;let a=Object.entries(i).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c$1={};for(let l of s){let d=l.author;c$1[d]||(c$1[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[d].count++,l.agent&&(c$1[d].hasAgent=true),l.timestamp>c$1[d].lastActive&&(c$1[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(At),hotSymbols:a,authors:Object.entries(c$1).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,r=await b$1(o.rootDir,t);return r?{handled:true,text:JSON.stringify(r,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:r,...s}=e,i={};for(let[c,l]of Object.entries(s))l!==void 0&&(i[c]=l);let a=await g$2(o.rootDir,t,i);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,r=e.verdict,s=e.notes,i=await b$1(o.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:r,assessed_by:It(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let m=process.env.PARADIGM_AGENT_ID;if(m&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:h}=await import('./agent-loader-W3RQJVW7.js');h(o.rootDir,m,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,d=i.confidence!=null?l-i.confidence:null,p=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:t,verdict:r,confidence:i.confidence??null,delta:d,deltaDescription:p,message:c?`Assessment recorded: ${r}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},r=await a$3(o.rootDir,t),s=r.filter(F=>F.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,p=0;for(let F of r){let C=F.assessment.verdict;c[C]++;let O=C==="correct"?1:C==="partial"?.5:0;l+=O,F.confidence!=null&&(d+=F.confidence,p+=Math.abs(O-F.confidence));}let m=i>0?l/i:0,h=a>0?d/a:null,x=a>0?l/i-d/a:null,f=a>0?1-p/a:null,P=e.groupBy,A;if(P&&i>0){let F=new Map;for(let C of r){let O=[];P==="symbol"?O=C.symbols_touched||[]:P==="tag"?O=C.tags||[]:P==="type"&&(O=[C.type||"agent-session"]);for(let E of O)F.has(E)||F.set(E,[]),F.get(E).push(C);}A=Array.from(F.entries()).map(([C,O])=>{let E=O.filter(N=>N.confidence!=null),w={correct:0,partial:0,incorrect:0},v=0,u=0,k=0;for(let N of O){let T=N.assessment.verdict;w[T]++;let S=T==="correct"?1:T==="partial"?.5:0;v+=S,N.confidence!=null&&(u+=N.confidence,k+=Math.abs(S-N.confidence));}return {key:C,total:O.length,accuracyRate:v/O.length,avgConfidence:E.length>0?u/E.length:null,calibrationScore:E.length>0?1-k/E.length:null,verdictBreakdown:w}}).sort((C,O)=>O.total-C.total);}let R=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&R.push($),f!=null&&(f>=.9?R.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):f>=.7?R.push("Good calibration \u2014 some room for improvement in confidence estimates."):f>=.5?R.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):R.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?R.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&R.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&R.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(m*1e3)/1e3,avgConfidence:h!=null?Math.round(h*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:f!=null?Math.round(f*1e3)/1e3:null,verdictBreakdown:c,...A?{groups:A}:{},insights:R},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let s=await i$1(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function wn(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function At(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function hs(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function bs(n,e,o){return n==="paradigm_captain_brief"?Sn(e,o):n==="paradigm_captain_debrief"?xn(e,o):n==="paradigm_captain_board"?Cn(e,o):{handled:false,text:""}}async function Sn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=I.join(e.rootDir,".paradigm"),i=I.join(s,".cid-session"),a=I.join(s,".cid-briefed");try{D.existsSync(a)&&D.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};D.mkdirSync(s,{recursive:!0}),D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=$n(o),l=[],d=new Set;for(let S of t)if(!d.has(S)){d.add(S);let b=$t(S);l.push({id:S,type:b,description:"Provided as anchor symbol"});}let p=[];try{for(let S of c.slice(0,3)){let g=m(e.index,S).slice(0,5);for(let y of g)if(!d.has(y.symbol)){d.add(y.symbol);let _=Tn(y.type);l.push({id:y.symbol,type:_,description:y.description||"",file:y.file}),p.push(y.symbol);}}}catch{}let m$1={directories:[],files:[]};try{let S=await lt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let b=JSON.parse(S.text);if(b.files)for(let g of b.files){let y=typeof g=="string"?g:g.path||g.file||"";y&&m$1.files.push(y);}if(b.directories)for(let g of b.directories){let y=typeof g=="string"?g:g.path||g.directory||"";y&&m$1.directories.push(y);}if(b.symbols)for(let g of b.symbols){let y=typeof g=="string"?g:g.id;y&&!d.has(y)&&(d.add(y),l.push({id:y,type:$t(y),description:typeof g=="object"&&g.description||""}));}}}catch{}let h=new Set(m$1.directories);for(let S of m$1.files){let b=I.dirname(S);b&&b!=="."&&h.add(b);}let x=l.slice(0,r==="deep"?5:3),f={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let b=await le("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(b.handled){let g=JSON.parse(b.text);if(g.analysis){for(let y of g.analysis.directlyAffected||[]){let _=y.symbol||y;_&&!f.affectedSymbols.includes(_)&&f.affectedSymbols.push(_);}for(let y of g.analysis.indirectlyAffected||[])y&&!f.affectedSymbols.includes(y)&&f.affectedSymbols.push(y);}if(g.affectedFlows?.affectedFlows)for(let y of g.affectedFlows.affectedFlows){let _=y.flowId||y;_&&!f.affectedFlows.includes(_)&&f.affectedFlows.push(_);}if(g.affectedGates)for(let y of g.affectedGates){let _=y.gate||y;_&&!f.affectedGates.includes(_)&&f.affectedGates.push(_);}g.impact==="high"&&(f.fragileSymbols.includes(S.id)||f.fragileSymbols.push(S.id));}}catch{}let P=[],A=En(o);if(A.length>0)try{let{handleGatesForRoute:S}=await import('./tools-HNJ7D5IO.js').catch(()=>({handleGatesForRoute:null})),b=I.join(e.rootDir,"portal.yaml");if(D.existsSync(b)){let g=D.readFileSync(b,"utf8");for(let y of A){let _=g.includes(y);P.push({route:y,gate:"^authenticated",declared:_});}}else for(let g of A)P.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let R=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),b=await Pt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(b.handled){let g=JSON.parse(b.text);if(g.antipatterns)for(let y of g.antipatterns.slice(0,3)){let _=y.pattern||y.description||y.text||String(y);_&&!R.includes(_)&&R.push(_);}if(g.wisdom?.antipatterns)for(let y of g.wisdom.antipatterns.slice(0,3)){let _=y.pattern||y.description||String(y);_&&!R.includes(_)&&R.push(_);}}}catch{}let $={matched:false};try{let S=await jt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let b=JSON.parse(S.text),g=b.matches||b.protocols||b.results||[];if(g.length>0){let y=g[0];$={matched:!0,id:y.id,name:y.name||y.title,steps:(y.steps||[]).slice(0,5).map(_=>typeof _=="string"?_:_.description||String(_))};}}}catch{}let F=[];if(r!=="quick")try{let S=l[0]?.id,b={limit:r==="deep"?5:3};S&&(b.symbol=S);let g=await je("paradigm_lore_search",b,e);if(g.handled){let _=JSON.parse(g.text).entries||[];for(let K of _.slice(0,3))F.push({id:K.id,summary:(K.summary||K.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let C=Array.from(h),O$1=0;for(let S of C){let b=I.join(e.rootDir,S,".purpose");if(D.existsSync(b))try{D.readFileSync(b,"utf8").trim().length>50&&O$1++;}catch{}}let E=C.length>0?O$1/C.length:.5,w=Wn(E),v=Ln(E,w,C.length),u=f.affectedSymbols.length+m$1.files.length,k=u>20?"large":u>8?"medium":u>2?"small":"tiny",N={territory:{directories:C.slice(0,10),files:m$1.files.slice(0,10),estimatedScope:k},symbols:l.slice(0,10),blastRadius:f,gates:P,protocol:$,warnings:R,coverage:{score:E,label:w,note:v},loreRefs:F,archMap:b$2(e.rootDir),renderedBrief:""};N.renderedBrief=Hn(N);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:E};D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(N,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function xn(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=I.join(e.rootDir,".paradigm"),c=I.join(a,".cid-briefed"),l=I.join(a,".pending-review"),d=new Set;for(let u of r){let k=I.dirname(u);k&&k!=="."&&d.add(k);}let p=0,m=d.size;for(let u of d){let k=I.join(e.rootDir,u,".purpose");if(D.existsSync(k))try{D.readFileSync(k,"utf8").trim().length>50&&p++;}catch{}}let h=m>0?p/m:1,x=[],f=[];for(let u of d){let k=I.join(e.rootDir,u,".purpose"),N=I.join(e.rootDir,u),T=false;if(D.existsSync(k))try{T=D.readFileSync(k,"utf8").trim().length>50;}catch{}if(T){if(r.some(b=>I.dirname(b)===u&&s.length>0)){f.push(u);try{let b=JSON.stringify({path:u,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});D.appendFileSync(l,b+`
|
|
6
|
-
`,"utf8");}catch{}}}else try{if(!D.existsSync(N))continue;let S=I.basename(u),b=Bn(S,u,r);D.writeFileSync(k,b,"utf8"),x.push(u),f.push(u);try{let g=JSON.stringify({path:u,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(y=>I.dirname(y)===u).join(", ")}`,timestamp:new Date().toISOString()});D.appendFileSync(l,g+`
|
|
7
|
-
`,"utf8");}catch{}}catch{}}let P=0;for(let u of d){let k=I.join(e.rootDir,u,".purpose");if(D.existsSync(k))try{D.readFileSync(k,"utf8").trim().length>50&&P++;}catch{}}let A=m>0?P/m:1,R="";try{let u=await je("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${t.slice(0,80)}`,summary:t,symbols_touched:s,files_modified:r,tags:["arc:cid-debrief",`orch:${o}`],meta:{orchestrationId:o,coverageScore:{before:h,after:A},coverageAdded:x,...i?{notes:i}:{}}},e);if(u.handled){let k=JSON.parse(u.text);R=k.id||k.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=_n(a),!$.ranThisSession)try{let{runPostflightLearning:u}=await import('./ambient-7HBJHJL2.js');await u(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a$1.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(u){$.selfHealError=u instanceof Error?u.message:String(u),a$1.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:k}=await import('./propose-block-ZEMEWJQF.js');await k("paradigm_propose_block",{claimant:"navigation",severity:"advise",reason:`Postflight learning did not run and Cid's self-heal failed: ${$.selfHealError}`,unblock_hint:"Run `paradigm_ambient_learn_postflight` manually, or inspect .paradigm/events/settlement-liveness.jsonl for the severed stage."},e),$.blockProposed=!0;}catch{}}let F=false;try{let u={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:A};D.mkdirSync(a,{recursive:!0}),D.writeFileSync(c,JSON.stringify(u,null,2),"utf8"),F=!0;}catch{}let C={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:h,after:A},newSymbols:s,touchedFiles:r,notes:i||""};try{let u=I.join(a,"events","session-log.jsonl");if(D.existsSync(u)){let T=D.readFileSync(u,"utf8").split(`
|
|
8
|
-
`).filter(b=>b.trim().length>0).slice(-50),S=new Map;for(let b of T)try{let g=JSON.parse(b),y=g.agentId||g.agent||g.role||"";if(!y)continue;S.has(y)||S.set(y,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let _=S.get(y),K=g.action||g.event||g.message||"";if(K&&_.contributions.push(String(K).slice(0,120)),Array.isArray(g.symbols))for(let te of g.symbols)_.symbolsTouched.add(String(te));let De=g.symbol||"";if(De&&_.symbolsTouched.add(De),Array.isArray(g.patterns))for(let te of g.patterns)_.patternsObserved.includes(String(te))||_.patternsObserved.push(String(te));}catch{}for(let[b,g]of S.entries())C.agentContributions.push({agentId:b,contribution:g.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(g.symbolsTouched).slice(0,10),patternsObserved:g.patternsObserved.slice(0,5)});}}catch{}C.agentContributions.length===0&&C.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]});let O$1={coverageAdded:x,delegatedToDocumentor:f,loreEntryId:R,coverageScore:{before:h,after:A,delta:A-h},stopHookCleared:F,postflight:$,sessionInsights:C},E=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
|
|
9
|
-
`),v=JSON.stringify(O$1,null,2)+`
|
|
10
|
-
`+E;return O(v.length,"paradigm_captain_debrief"),{handled:true,text:v}}var vn=I.join("events","settlement-liveness.jsonl"),kn=360*60*1e3;function _n(n){let e=I.join(n,vn);if(!D.existsSync(e))return false;try{let t=D.readFileSync(e,"utf8").split(`
|
|
11
|
-
`).filter(s=>s.trim().length>0),r=Date.now()-kn;for(let s of t.slice(-50))try{let i=JSON.parse(s),a=i.ts?new Date(i.ts).getTime():NaN;if(Number.isNaN(a)||a<r)continue;if(i.stages?.runPostflightLearning==="ok")return !0}catch{}}catch{return false}return false}async function Cn(n,e){let o=n.action||"read";if(o==="claim")return On(n,e);if(o==="advance")return Nn(n,e);let t=await In(e.rootDir,{},e),r=JSON.stringify(t,null,2);return O(r.length,"paradigm_captain_board"),{handled:true,text:r}}function Pn(n,e){return n.settledAt?n.crashed_at||e.some(t=>t.crashed_at)?"crashed":"settled":e.length===0?"pending":e.some(t=>t.status==="in-progress")||n.status==="in-progress"?"in-progress":"pending"}function jn(n){return [...n].sort((e,o)=>{let t=e.stage??0,r=o.stage??0;if(t!==r)return t-r;let s=e.dependsOn?.length??0,i=o.dependsOn?.length??0;return s!==i?s-i:e.id.localeCompare(o.id)})}async function Dn(n,e){let o=Et(n).slice(0,3),t=[];for(let r of o)try{let s=await le("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var Rn=/[#$^!~][a-z][a-z0-9-]*/gi;function Et(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(Rn)||[];for(let t of o)e.add(t);return Array.from(e)}async function Fn(n,e){let o=Et(n).slice(0,3),t=0,r=[];for(let s of o)try{let i=await le("paradigm_ripple",{symbol:s,depth:2,response_format:"concise"},e);if(i.handled){let a=JSON.parse(i.text),c=a.analysis?.directlyAffected?.length??0,l=a.analysis?.indirectlyAffected?.length??0;t+=c*2+l,a.impact==="high"&&!r.includes(s)&&r.push(s);}}catch{}return {score:t,fragile:r}}var Nt={high:0,medium:1,low:2};async function In(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-IGQQ6ZFL.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(m){a$1.flow("$captain-board").warn("Board task load failed",{error:m instanceof Error?m.message:String(m)});}let i=s.filter(m=>m.external_ref?.kind==="orchestration"&&!m.parentTaskId&&!m.settledAt),a=[];for(let m of i){let h=jn(s.filter(f=>f.parentTaskId===m.id)),x=[];for(let f of h){let P=t?await Dn(f,t):[];x.push({taskId:f.id,blurb:f.blurb,stage:f.stage,status:f.status,claimant:f.claimant,dependsOn:f.dependsOn||[],fragileSymbols:P});}a.push({epicTaskId:m.id,blurb:m.blurb,runStatus:Pn(m,h),settledAt:m.settledAt,nodes:x});}let c=s.filter(m=>m.status==="open"&&!m.claimant),l=[];for(let m of c){let{score:h,fragile:x}=t?await Fn(m,t):{score:0,fragile:[]},f;e.proposeClaimants&&(f=await An(m,n)),l.push({taskId:m.id,blurb:m.blurb,priority:m.priority,tags:m.tags||[],rippleScore:h,fragileSymbols:x,proposedClaimant:f});}l.sort((m,h)=>{if(h.rippleScore!==m.rippleScore)return h.rippleScore-m.rippleScore;let x=(Nt[m.priority]??1)-(Nt[h.priority]??1);return x!==0?x:h.taskId.localeCompare(m.taskId)});let d=s.filter(m=>m.status==="in-progress").length,p=s.filter(m=>m.status==="open").length;return {runs:a,unclaimed:l,summary:{runs:a.length,open:p,inFlight:d,unclaimed:l.length}}}async function An(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-G5MAY6IA.js'),r=t(e);if(!r?.agents)return;let s=[n.blurb,...n.tags||[]].join(" "),i=o(s,r.agents);return i.length===0?void 0:{kind:"archetype",ref:i[0].name}}catch{return}}async function On(n,e){let o=n.taskId,t=n.claimant;if(!o||!t?.kind||!t?.ref)return {handled:true,text:JSON.stringify({ok:false,error:"claim requires taskId and claimant {kind, ref}"})};let{loadTask:r,updateTask:s}=await import('./task-loader-IGQQ6ZFL.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=i.claimant;if(a&&a.kind!=="archetype"&&t.kind==="archetype")return a$1.flow("$captain-board").info("Claim rejected: archetype cannot override human/peer claim",{taskId:o,existing:a.kind,proposed:t.kind}),{handled:true,text:JSON.stringify({ok:false,error:`task ${o} is claimed by ${a.kind}:${a.ref}; archetype proposal cannot override`,claimant:a})};let c=await s(e.rootDir,o,{claimant:t});return a$1.flow("$captain-board").info("Captain claim written",{taskId:o,claimant:t,ok:c}),{handled:true,text:JSON.stringify({ok:c,taskId:o,claimant:t,status:"open"})}}async function Nn(n,e){let o=n.taskId,t=n.blockedOn;if(!o||!t)return {handled:true,text:JSON.stringify({ok:false,error:"advance requires taskId and blockedOn (v7.0 has no 'blocked' status \u2014 advance records a reason only)"})};let{loadTask:r,updateTask:s}=await import('./task-loader-IGQQ6ZFL.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=await s(e.rootDir,o,{blocked_on:t});return a$1.flow("$captain-board").info("Captain advance: blocked_on recorded (status unchanged)",{taskId:o,blockedOn:t,status:i.status,ok:a}),{handled:true,text:JSON.stringify({ok:a,taskId:o,blocked_on:t,status:i.status})}}function $n(n){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),o=n.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],t=n.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(s=>s.toLowerCase()).filter(s=>s.length>2&&!e.has(s));return [...new Set([...o,...t])].slice(0,6)}function En(n){let e=[],o=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,t;for(;(t=o.exec(n))!==null;)e.push(t[1]);let r=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(t=r.exec(n))!==null;)e.includes(t[0])||e.push(t[0]);return e}function $t(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Tn(n){switch(n){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function Wn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Ln(n,e,o){let t=Math.round(n*100);switch(e){case "sparse":return `${t}% of ${o} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${t}% of ${o} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${t}% of ${o} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${t}% of ${o} director(ies) covered. Area is fully mapped.`}}function Hn(n){let e=[],o="\u2501".repeat(52);e.push(`${o}`),e.push("");let t=n.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${t}`);let r=n.symbols.slice(0,5).map(d=>d.id).join(", ")||"(none found)";e.push(`Symbols: ${r}`);let s=n.blastRadius.affectedFiles.length+n.territory.files.length,i=n.blastRadius.affectedFlows.length,a=n.blastRadius.affectedGates.length,c=n.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${n.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${s} files \xB7 ${i} flows \xB7 ${a} gates${c}`),n.gates.length>0){let d=n.gates.slice(0,2).map(p=>`${p.route} \u2192 ${p.gate} (${p.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${d.join("; ")}`);}if(n.protocol.matched){let d=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${d} \u2014 matched`);}else e.push("Protocol: (none matched)");n.warnings.length>0&&e.push(`Warnings: "${n.warnings[0].slice(0,80)}"`);let l=Math.round(n.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${n.coverage.label}`),e.push(""),e.push(`${o}`),e.join(`
|
|
12
|
-
`)}function Bn(n,e,o){let r=o.filter(s=>I.dirname(s)===e).slice(0,3).map(s=>`# - ${I.basename(s)}`).join(`
|
|
13
|
-
`);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
|
|
14
|
-
# Delegate to Scribe (Documentor) for rich documentation
|
|
15
|
-
name: ${n}
|
|
16
|
-
description: "TODO: describe what this directory/module does"
|
|
17
|
-
context:
|
|
18
|
-
- "Stub created by Cid during coverage audit \u2014 update with real context"
|
|
19
|
-
${r?`# Key files touched:
|
|
20
|
-
${r}`:""}
|
|
21
|
-
components:
|
|
22
|
-
${n}:
|
|
23
|
-
description: "TODO: describe this component"
|
|
24
|
-
tags: []
|
|
25
|
-
`}export{ss as A,je as B,hs as C,bs as D,In as E,An as F,dn as a,wt as b,wo as c,mn as d,So as e,un as f,xo as g,xe as h,Fo as i,fe as j,Io as k,Zn as l,lt as m,pt as n,mt as o,ut as p,mo as q,le as r,Bo as s,Pt as t,Go as u,jt as v,zo as w,Ce as x,Rt as y,Vo as z};
|
package/dist/chunk-MBPLJKE5.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {AsyncLocalStorage}from'async_hooks';var f={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"},g="\x1B[1m",c="\x1B[0m";function d(){let t=new Date,r=String(t.getHours()).padStart(2,"0"),e=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return `${r}:${e}:${s}.${o}`}function y(t){return !t||Object.keys(t).length===0?"":" "+JSON.stringify(t)}function v(t,r,e,s,o,i){let n=f[t],a=t.toUpperCase().padEnd(5),h=d(),p=y(i?{correlationId:i,...o}:o);return `${n}${h}${c} ${g}${r}${c} ${n}${a}${c} ${s}${p}`}function S(t,r,e,s,o,i){let n={timestamp:new Date().toISOString(),level:t,symbol:r,symbolType:e,message:s,...o};return i&&(n.correlationId=i),JSON.stringify(n)}var w=new AsyncLocalStorage;function $(){return w.getStore()}var m={debug:0,info:1,warn:2,error:3};function L(){let t=typeof process<"u"?process.env:{},r=t.LOG_LEVEL;return r&&m[r]!==void 0?r:t.NODE_ENV==="production"?"info":"debug"}function O(){let t=typeof process<"u"?process.env:{};return t.PARADIGM_LOG_FORMAT==="json"||t.NODE_ENV==="production"?"json":"pretty"}function T(){let r=(typeof process<"u"?process.env:{}).PARADIGM_SYMBOLS;return r?r.split(",").map(e=>e.trim()).filter(Boolean):null}var D=class{constructor(t){this.emit=t,this.startTime=Date.now();}startTime;success(t,r){this.end("info",t,r);}error(t,r){this.end("error",t,r);}end(t,r,e){let s=Date.now()-this.startTime;this.emit(t,r,{...e,duration:`${s}ms`});}},l=class{constructor(t,r,e,s,o,i,n=[]){this.symbol=t,this.symbolType=r,this.minLevel=e,this.symbolFilter=s,this.format=o,this.output=i,this.transports=n;}debug(t,r){this.emit("debug",t,r);}info(t,r){this.emit("info",t,r);}warn(t,r){this.emit("warn",t,r);}error(t,r){this.emit("error",t,r);}start(t,r){return this.emit("info",t,r),new D((e,s,o)=>this.emit(e,s,o))}emit(t,r,e){if(m[t]<m[this.minLevel])return;if(this.symbolFilter){let n=this.symbol.charAt(0);if(!this.symbolFilter.includes(n))return}let s=$(),i=(this.format==="json"?S:v)(t,this.symbol,this.symbolType,r,e,s);if(this.output(i),this.transports.length>0){let n={level:t,symbol:this.symbol,symbolType:this.symbolType,message:r,data:e,correlationId:s,timestamp:new Date().toISOString()};for(let a of this.transports)a.send(n);}}},u=class{level;symbolFilter;format;output;transports;constructor(t){this.level=t?.level??L(),this.symbolFilter=t?.symbols??T(),this.format=t?.format??O(),this.output=t?.output??(r=>console.log(r)),this.transports=t?.transports??[];}addTransport(t){this.transports.push(t);}removeTransport(t){let r=this.transports.indexOf(t);r!==-1&&this.transports.splice(r,1);}component(t){return this.create(t,"component","#")}gate(t){return this.create(t,"gate","^")}signal(t){return this.create(t,"signal","!")}flow(t){return this.create(t,"flow","$")}aspect(t){return this.create(t,"aspect","~")}raw(t){return new l(t,"raw",this.level,this.symbolFilter,this.format,this.output,this.transports)}create(t,r,e){let s=t.startsWith(e)?t:`${e}${t}`;return new l(s,r,this.level,this.symbolFilter,this.format,this.output,this.transports)}};new u;var N=new u({output:t=>process.stderr.write(t+`
|
|
3
|
-
`)});export{N as a};
|
package/dist/chunk-QEQCPVF5.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {c,b as b$1}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as l from'path';import*as w from'os';import*as f from'js-yaml';var z={};c(z,{addNotebookEntry:()=>C,classifyNotebookScope:()=>E,incrementApplied:()=>v,loadNotebookEntries:()=>N,normalizeConcept:()=>u,promoteFromLore:()=>P,searchNotebooks:()=>$});function u(o){if(!o)return "";let t=o.trim();return t=t.replace(/^symbol:/i,""),t=t.replace(/^[#$^!~@&%?]/,""),t.trim().toLowerCase()}function N(o,t,n){let s=new Map,a=l.join(y,o);k(a,s);let e=l.join(t,b,o);k(e,s);let r=Array.from(s.values());if(n?.concepts&&n.concepts.length>0){let p=new Set(n.concepts.map(u));r=r.filter(c=>c.concepts.some(m=>p.has(u(m))));}if(n?.tags&&n.tags.length>0){let p=new Set(n.tags.map(c=>c.toLowerCase()));r=r.filter(c=>c.tags.some(m=>p.has(m.toLowerCase())));}return r.sort((p,c)=>c.appliedCount-p.appliedCount)}function k(o,t){if(i.existsSync(o))try{let n=i.readdirSync(o).filter(s=>s.startsWith(_)&&s.endsWith(h));for(let s of n)try{let a=i.readFileSync(l.join(o,s),"utf-8"),e=f.load(a);e?.id&&t.set(e.id,e);}catch{}}catch{}}function $(o,t,n){let s=N(o,n),a=t.toLowerCase();return s.filter(e=>e.context.toLowerCase().includes(a)||e.snippet.toLowerCase().includes(a)||e.concepts.some(r=>r.toLowerCase().includes(a))||e.tags.some(r=>r.toLowerCase().includes(a)))}function E(o){let t=[o.context,o.snippet,...o.concepts,...o.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(s=>t.includes(s))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function C(o,t,n,s){let a=new Date().toISOString(),e=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),p=`nb-${o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${e}`,c=t.scope??E({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),m=Array.from(new Set((t.concepts||[]).map(u).filter(Boolean))),g={...t,concepts:m,id:p,scope:c,publishable:t.publishable??true,appliedCount:0,created:a,updated:a},d=n==="global"?l.join(y,o):l.join(s||process.cwd(),b,o);i.existsSync(d)||i.mkdirSync(d,{recursive:true});let j=`${p}${h}`,S=l.join(d,j),x=f.dump(g,{lineWidth:120,noRefs:true,sortKeys:false});return i.writeFileSync(S,x,"utf-8"),{entry:g,filePath:S}}async function P(o,t,n,s="global"){let{loadLoreEntry:a}=await import('./lore-loader-PXFKMKAN.js'),e=await a(n,t);if(!e)return null;let r=[];if(e.symbols_touched)for(let m of e.symbols_touched){let g=m.replace(/^[#$^!~]/,"").toLowerCase();r.push(g);}let p=e.summary||"";e.body&&(p+=`
|
|
3
|
-
|
|
4
|
-
`+e.body);let c={source:"lore",loreEntryId:t,originProject:l.basename(n),createdBy:o};return C(o,{context:e.title||`Promoted from ${t}`,snippet:p,provenance:c,confidence:e.confidence??.7,concepts:r,tags:e.tags||[]},s,n)}function v(o,t,n){let s=l.join(n,b,o),a=l.join(y,o);for(let e of [s,a]){let r=l.join(e,`${t}${h}`);if(i.existsSync(r))try{let p=i.readFileSync(r,"utf-8"),c=f.load(p);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),i.writeFileSync(r,f.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var y,b,_,h,T=b$1(()=>{y=l.join(w.homedir(),".paradigm","notebooks"),b=".paradigm/notebooks",_="nb-",h=".yaml";});export{u as a,N as b,$ as c,E as d,C as e,P as f,v as g,z as h,T as i};
|
package/dist/chunk-QGZRM6ZB.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {c as c$1,b as b$1}from'./chunk-5TAVYPOV.js';import*as s from'fs';import*as c from'path';import*as g from'js-yaml';var b={};c$1(b,{getJournalStats:()=>S,loadAllJournalEntries:()=>E,loadJournalEntries:()=>f,loadJournalEntry:()=>J,recordJournalEntry:()=>h});function m(e){let r=process.env.HOME||process.env.USERPROFILE||"";return c.join(r,".paradigm","agents",e,"journal")}function y(){let e=new Date,r=e.toISOString().slice(0,10),i=e.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${r}-${i}-${o}`}function h(e,r){let i=new Date,o=y(),a={id:o,agent:e,timestamp:i.toISOString(),...r},t=m(e);s.mkdirSync(t,{recursive:true});let n=c.join(t,`${o}.yaml`);return s.writeFileSync(n,g.dump(a,{lineWidth:120,noRefs:true}),"utf8"),a}function f(e,r){let i=m(e);if(!s.existsSync(i))return [];let o=[],a=s.readdirSync(i).filter(n=>n.endsWith(".yaml"));for(let n of a)try{let l=s.readFileSync(c.join(i,n),"utf8"),u=g.load(l);u&&u.id&&o.push(u);}catch{}let t=o;return r?.trigger&&(t=t.filter(n=>n.trigger===r.trigger)),r?.project&&(t=t.filter(n=>n.project===r.project)),r?.transferable!==void 0&&(t=t.filter(n=>n.transferable===r.transferable)),r?.tag&&(t=t.filter(n=>n.tags?.some(l=>l.startsWith(r.tag)))),r?.dateFrom&&(t=t.filter(n=>n.timestamp>=r.dateFrom)),r?.dateTo&&(t=t.filter(n=>n.timestamp<=r.dateTo)),t.sort((n,l)=>l.timestamp.localeCompare(n.timestamp)),r?.limit&&(t=t.slice(0,r.limit)),t}function J(e,r){let i=m(e),o=c.join(i,`${r}.yaml`);if(!s.existsSync(o))return null;let a=s.readFileSync(o,"utf8");return g.load(a)}function E(e){let r=process.env.HOME||process.env.USERPROFILE||"",i=c.join(r,".paradigm","agents");if(!s.existsSync(i))return [];let o=[],a=s.readdirSync(i,{withFileTypes:true}).filter(t=>t.isDirectory());for(let t of a){if(e?.agent&&t.name!==e.agent)continue;let n=f(t.name,e);o.push(...n);}return o.sort((t,n)=>n.timestamp.localeCompare(t.timestamp)),e?.limit?o.slice(0,e.limit):o}function S(e){let r=f(e),i={},o={},a=0;for(let t of r)i[t.trigger]=(i[t.trigger]||0)+1,o[t.project]=(o[t.project]||0)+1,t.transferable&&a++;return {total:r.length,byTrigger:i,byProject:o,transferableCount:a,recentInsights:r.slice(0,5).map(t=>({id:t.id,trigger:t.trigger,insight:t.insight.slice(0,200),timestamp:t.timestamp}))}}var j=b$1(()=>{});export{h as a,f as b,J as c,E as d,S as e,b as f,j as g};
|
package/dist/chunk-QO7YPQXC.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {b as b$1,c as c$1,d}from'./chunk-5TAVYPOV.js';import*as c from'fs';import*as l from'path';import*as y from'js-yaml';var g,R=b$1(()=>{g={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]};});var M={};c$1(M,{getAllStates:()=>ie,getConfig:()=>te,getState:()=>G,incrementFailure:()=>se,invalidateGraduationCache:()=>ae,isGraduated:()=>oe,loadGraduation:()=>p,markNeverGraduate:()=>ne,saveGraduation:()=>H,setTier:()=>re});function A(e){return l.join(e,".paradigm","graduation.yaml")}function p(e){let t=l.resolve(e);if(m&&b===t&&Date.now()-v<ee)return m;let o=A(t),i;if(c.existsSync(o))try{let r=c.readFileSync(o,"utf8");i=y.load(r);}catch{i={version:"1.0",config:{},states:{}};}else i={version:"1.0",config:{},states:{}};return i.version||(i.version="1.0"),i.config||(i.config={}),i.states||(i.states={}),m=i,b=t,v=Date.now(),i}function H(e,t){let o=l.resolve(e),i=A(o),r=l.dirname(i);c.existsSync(r)||c.mkdirSync(r,{recursive:true});let n=y.dump(t,{lineWidth:120,noRefs:true,sortKeys:true});c.writeFileSync(i,n,"utf8"),m=t,b=o,v=Date.now();}function te(e){let t=p(e);return {...g,...t.config,thresholds:{...g.thresholds,...t.config?.thresholds},demotion:{...g.demotion,...t.config?.demotion},neverGraduate:t.config?.neverGraduate??g.neverGraduate}}function w(e){return {habitId:e,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function G(e,t){let i=p(e).states[t];return i?{...w(t),...i,habitId:t}:w(t)}function ie(e){let t=p(e),o={};for(let[i,r]of Object.entries(t.states))o[i]={...w(i),...r,habitId:i};return o}function oe(e,t){return G(e,t).tier==="hook"}function re(e,t,o,i){let r=p(e),n=r.states[t]||{};r.states[t]={...n,tier:o,previousTier:n.tier||"habit",...o==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...o==="habit"&&n.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...i},H(e,r);}function ne(e,t){let o=p(e);o.states[t]||(o.states[t]={}),o.states[t].neverGraduate=true,o.states[t].tier="habit",H(e,o);}function se(e,t){let o=p(e);o.states[t]||(o.states[t]={});let i=(o.states[t].failureCount||0)+1;return o.states[t].failureCount=i,H(e,o),i}function ae(){m=null,b=null,v=0;}var m,b,v,ee,j=b$1(()=>{R();m=null,b=null,v=0,ee=3e4;});var E=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"commit-message-symbols",name:"Commit Message Format",description:"Commit messages should follow type(#symbol): format and include a Symbols: trailer",category:"documentation",trigger:"on-commit",severity:"advisory",check:{type:"commit-message-format",params:{messagePatterns:["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"]}},enabled:true},{id:"flow-coverage-for-multi-component",name:"Flow Coverage",description:"Changes spanning 3+ components should have a documented $flow",category:"documentation",trigger:"postflight",severity:"advisory",check:{type:"flow-coverage",params:{minSteps:3}},enabled:true},{id:"context-session-awareness",name:"Context Awareness",description:"Use session recovery or context check tools for session continuity",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"context-checked",params:{contextTools:["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]}},enabled:true},{id:"aspect-anchors-valid",name:"Aspect Anchors Valid",description:"Aspects touched during the session should have their code anchors validated",category:"verification",trigger:"postflight",severity:"advisory",check:{type:"aspect-anchored",params:{checkAnchors:true}},enabled:true}];var V=E,Y=30*1e3;function K(e){try{let t=l.join(e,".paradigm","config.yaml");if(c.existsSync(t)){let o=c.readFileSync(t,"utf8"),r=y.load(o)?.limits;if(r?.habitsCacheTtlMs&&typeof r.habitsCacheTtlMs=="number")return r.habitsCacheTtlMs}}catch{}return Y}var k=new Map;function z(e){let t=l.resolve(e),o=k.get(t),i=K(t);if(o&&Date.now()-o.loadedAt<i)return o.habits;let r=Q(t);return k.set(t,{habits:r,loadedAt:Date.now()}),r}function Q(e){let t=new Map;for(let s of V)t.set(s.id,{...s});let o=process.env.HOME||process.env.USERPROFILE||"~",i=S(l.join(o,".paradigm","habits.yaml"));i&&D(t,i);let r=T(l.join(o,".paradigm","habits"));for(let s of r)t.set(s.id,s);let n=S(l.join(e,".paradigm","habits.yaml"));n&&D(t,n);let u=T(l.join(e,".paradigm","habits"));for(let s of u)t.set(s.id,s);return Array.from(t.values())}function T(e){if(!c.existsSync(e))return [];try{let t=c.readdirSync(e).filter(i=>i.endsWith(".habit")).sort(),o=[];for(let i of t)try{let r=c.readFileSync(l.join(e,i),"utf8"),n=y.load(r);n?.id&&n?.name&&o.push(n);}catch{}return o}catch{return []}}function S(e){if(!c.existsSync(e))return null;try{let t=c.readFileSync(e,"utf8");return y.load(t)}catch{return null}}function D(e,t){if(t.habits)for(let o of t.habits)e.set(o.id,{...o});if(t.overrides)for(let[o,i]of Object.entries(t.overrides)){let r=e.get(o);r&&J(r,i);}}function J(e,t){t.severity!==void 0&&(e.severity=t.severity),t.enabled!==void 0&&(e.enabled=t.enabled);}function X(e){return e.filter(t=>t.enabled)}function Z(e){let t=l.resolve(e);k.delete(t);}var le=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"confidence-on-decisions",name:"Confidence on Decisions",description:"When recording lore, include a confidence score (0.0-1.0) to enable calibration tracking over time",category:"documentation",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_lore_record"]}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"university-content-valid",name:"University Content Valid",description:"Validate university content integrity when files in symbol-covered areas change",category:"quality",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_validate"]}},enabled:true},{id:"university-onboarded",name:"University Onboarding",description:"Call paradigm_university_onboard at session start for project-specific learning content",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_onboard"]}},enabled:false},{id:"orchestration-required",name:"Orchestrate Complex Tasks",description:"Tasks affecting 3+ files or touching security symbols should use paradigm_orchestrate_inline to determine which agents are needed. Ensures security review, test coverage, and documentation.",category:"collaboration",trigger:"preflight",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_orchestrate_inline"]}},enabled:true},{id:"agent-coverage-validated",name:"Validate Agent Involvement",description:"After completing work, verify that agents with relevant expertise were consulted. Check nominations that were surfaced but not acted on.",category:"collaboration",trigger:"postflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ambient_nominations","paradigm_agent_list"]}},enabled:true},{id:"hot-mode-incident",name:"Incident Response Acknowledgment",description:"During incident response, orchestration enforcement is waived. But a post-incident lore entry is required and a postflight review should be scheduled.",category:"collaboration",trigger:"on-stop",severity:"advisory",check:{type:"lore-recorded"},enabled:true}];function ce(e,t){return e.filter(o=>o.enabled&&o.trigger===t)}new Set(le.map(e=>e.id));function F(e,t,o,i,r){let n=ce(e,t);i&&(n=n.filter(a=>!a.platforms||a.platforms.includes(i)));let u=0;if(r)try{let{isGraduated:a}=(j(),d(M)),O=n.length;n=n.filter(q=>!a(r,q.id)),u=O-n.length;}catch{}let s=n.map(a=>ue(a,o)),W=s.filter(a=>a.result==="followed").length,I=s.filter(a=>a.result==="skipped").length,N=s.filter(a=>a.result==="partial").length,_=s.filter(a=>a.result==="skipped"&&a.habit.severity==="block").length;return {trigger:t,evaluations:s,summary:{total:s.length,followed:W,skipped:I,partial:N,blockingViolations:_},blocksCompletion:_>0}}function $(e){return {toolsCalled:e.toolsCalled||[],filesModified:e.filesModified||[],symbolsTouched:e.symbolsTouched||[],loreRecorded:e.loreRecorded||false,hasPortalRoutes:e.hasPortalRoutes||false,taskAddsRoutes:e.taskAddsRoutes||false,taskDescription:e.taskDescription,gitClean:e.gitClean}}function ue(e,t){switch(e.check.type){case "tool-called":return fe(e,t);case "file-exists":return pe(e,t);case "file-modified":return be(e,t);case "lore-recorded":return ge(e,t);case "symbols-registered":return me(e,t);case "gates-declared":return he(e,t);case "tests-exist":return ye(e,t);case "git-clean":return ve(e,t);case "commit-message-format":return Ce(e,t);case "flow-coverage":return He(e,t);case "context-checked":return ke(e,t);case "aspect-anchored":return we(e,t);default:return {habit:e,result:"partial",reason:`Unknown check: ${e.check.type}`}}}function fe(e,t){let o=e.check.params.tools||[];if(o.length===0)return {habit:e,result:"followed",reason:"No tools required"};let i=o.filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, habit not applicable"}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] were called before modifying code`}}function pe(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};if(t.filesModified.some(r=>r.endsWith(".purpose")||r.includes(".paradigm/")))return {habit:e,result:"followed",reason:"Purpose files updated"};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".yml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/"));return i.length===0?{habit:e,result:"followed",reason:"Only non-source files modified"}:{habit:e,result:"skipped",reason:`${i.length} source file(s) without .purpose updates`,evidence:i.slice(0,5)}}function ge(e,t){let o=t.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return o.length<3?{habit:e,result:"followed",reason:"Session not significant (< 3 source files)"}:t.loreRecorded||t.toolsCalled.includes("paradigm_lore_record")?{habit:e,result:"followed",reason:"Lore recorded"}:{habit:e,result:"skipped",reason:`${o.length} source files modified, no lore entry`,evidence:o.slice(0,5)}}function me(e,t){if(t.symbolsTouched.length===0)return {habit:e,result:"followed",reason:"No symbols touched"};let i=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Purpose tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"partial",reason:`${t.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function he(e,t){if(!t.taskAddsRoutes)return {habit:e,result:"followed",reason:"No routes added"};if(t.hasPortalRoutes)return {habit:e,result:"followed",reason:"Portal.yaml has routes"};let i=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Gate tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:"Routes added without gate declarations"}}function ye(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=t.filesModified.filter(r=>r.includes(".test.")||r.includes(".spec.")||r.includes("/tests/")||r.includes("/test/")||r.includes("__tests__"));if(o.length>0)return {habit:e,result:"followed",reason:`Test files: ${o.length}`,evidence:o.slice(0,5)};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/")&&!r.includes("node_modules/"));return i.length===0?{habit:e,result:"followed",reason:"No source files to test"}:{habit:e,result:"partial",reason:`${i.length} source file(s), no test files updated`,evidence:i.slice(0,5)}}function be(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=e.check.params.patterns||[];if(o.length===0)return {habit:e,result:"followed",reason:"No patterns specified"};if(e.trigger==="on-stop"&&e.severity==="block"){let r=t.filesModified.filter(n=>o.some(u=>n.includes(u)||l.basename(n)===u));return r.length>0?{habit:e,result:"followed",reason:`Matching files: ${r.join(", ")}`,evidence:r}:{habit:e,result:"partial",reason:`None of [${o.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let i=t.filesModified.filter(r=>o.some(n=>r.includes(n)||l.basename(r)===n));return i.length>0?{habit:e,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] found in modified files`}}function ve(e,t){return t.filesModified.length===0?{habit:e,result:"followed",reason:"No files modified"}:e.trigger==="on-stop"?{habit:e,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:t.gitClean===void 0?{habit:e,result:"partial",reason:"Git status not available"}:t.gitClean?{habit:e,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:e,result:"skipped",reason:"Uncommitted changes in working tree"}}function Ce(e,t){if(!t.commitMessage)return {habit:e,result:"followed",reason:"No commit message to check (not a commit trigger)"};let o=e.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],i=o.filter(r=>new RegExp(r,"m").test(t.commitMessage));if(i.length===o.length)return {habit:e,result:"followed",reason:"Commit message matches all required patterns",evidence:i};if(i.length>0){let r=o.filter(n=>!new RegExp(n,"m").test(t.commitMessage));return {habit:e,result:"partial",reason:`Matches ${i.length}/${o.length} patterns. Missing: ${r.join(", ")}`}}return {habit:e,result:"skipped",reason:"Commit message does not match required format patterns"}}function He(e,t){let o=t.symbolsTouched.filter(n=>n.startsWith("#"));if(o.length<3)return {habit:e,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(t.hasFlowCoverage)return {habit:e,result:"followed",reason:"Flow coverage exists for multi-component changes"};let r=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(n=>t.toolsCalled.includes(n));return r.length>0?{habit:e,result:"followed",reason:`Flow tools called: ${r.join(", ")}`,evidence:r}:{habit:e,result:"skipped",reason:`${o.length} components touched without flow coverage`,evidence:o.slice(0,5)}}function ke(e,t){let i=(e.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Context tools called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, context check not applicable"}:{habit:e,result:"skipped",reason:"No context/session tools called during session"}}function we(e,t){let o=t.symbolsTouched.filter(i=>i.startsWith("~"));return o.length===0?{habit:e,result:"followed",reason:"No aspects touched"}:t.aspectAnchorsValid===true?{habit:e,result:"followed",reason:"Aspect anchors validated and valid"}:t.toolsCalled.includes("paradigm_aspect_check")?{habit:e,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:e,result:"skipped",reason:`${o.length} aspect(s) touched without anchor validation`,evidence:o.slice(0,5)}}export{z as a,X as b,Z as c,F as d,$ as e};
|