@a-company/paradigm 5.37.8 → 5.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/{accept-orchestration-SBZVK3H4.js → accept-orchestration-OATWIRHP.js} +1 -1
  2. package/dist/{aggregate-W66DM3GA.js → aggregate-A5S5MTCC.js} +1 -1
  3. package/dist/{beacon-5QVYV5DF.js → beacon-QVUD3MGP.js} +1 -1
  4. package/dist/{chunk-SI6SV76D.js → chunk-3DZK54RU.js} +72 -19
  5. package/dist/{chunk-KFNHCQ4R.js → chunk-4L7665QV.js} +1 -1
  6. package/dist/chunk-4VKSEOXZ.js +6 -0
  7. package/dist/{chunk-CHVQNRRT.js → chunk-5QOCKWK5.js} +1 -1
  8. package/dist/chunk-HOBHJPTL.js +24 -0
  9. package/dist/{chunk-T6IDXUUA.js → chunk-LWAIVOSF.js} +1 -1
  10. package/dist/chunk-NQ47TA6C.js +111 -0
  11. package/dist/{chunk-G7XFK2GI.js → chunk-RBLK34IA.js} +1 -1
  12. package/dist/chunk-RN4VE6P3.js +521 -0
  13. package/dist/{chunk-SUU6M4JH.js → chunk-TOYQ2QCB.js} +1 -1
  14. package/dist/{chunk-LBQBWIEX.js → chunk-Y4P4SGZV.js} +1 -1
  15. package/dist/chunk-ZJQY5PPP.js +7 -0
  16. package/dist/{commands-LMUD5L6R.js → commands-ANRJNG2W.js} +1 -1
  17. package/dist/compliance-D7GD6ZYC.js +6 -0
  18. package/dist/{constellation-CG7C4WFE.js → constellation-NWLXYATA.js} +1 -1
  19. package/dist/{cost-IDNVMAEV.js → cost-24UZSS2P.js} +1 -1
  20. package/dist/{diff-JVEYCXUC.js → diff-YGHBIJY5.js} +1 -1
  21. package/dist/dist-JZZJLVMR.js +2 -0
  22. package/dist/{dist-3ZCH25SG.js → dist-OG6MM4VY.js} +1 -1
  23. package/dist/dist-SE67SOXB.js +2 -0
  24. package/dist/doctor-WMVULMQD.js +2 -0
  25. package/dist/{flow-POQP27WA.js → flow-FVZR3YJ4.js} +1 -1
  26. package/dist/{hooks-IG2GOAHP.js → hooks-TFMMMB2H.js} +1 -1
  27. package/dist/index.js +5 -5
  28. package/dist/init-XYB62Q3X.js +2 -0
  29. package/dist/{integrity-UYDOOJDP.js → integrity-ROO3G43N.js} +1 -1
  30. package/dist/mcp.js +18 -10
  31. package/dist/{migrate-IBDE7VK4.js → migrate-Z5UQN57G.js} +1 -1
  32. package/dist/{orchestrate-RCAMBOIB.js → orchestrate-M5PBZBJQ.js} +1 -1
  33. package/dist/portal-check-ZMLVBIGW.js +8 -0
  34. package/dist/portal-compliance-6YR27IQU.js +2 -0
  35. package/dist/{probe-B22G2JKF.js → probe-3FTG6LYO.js} +1 -1
  36. package/dist/{reindex-FO5VMZVQ.js → reindex-I6LPAKCC.js} +1 -1
  37. package/dist/{review-6UAH6V3R.js → review-VMSX2PKI.js} +1 -1
  38. package/dist/{ripple-ZGDITCGB.js → ripple-FNZI47SH.js} +1 -1
  39. package/dist/sentinel.js +1 -1
  40. package/dist/{setup-3F5IK7MO.js → setup-FEWSYS3Y.js} +2 -2
  41. package/dist/{shift-CZMQWZWP.js → shift-PC6C7NUX.js} +4 -4
  42. package/dist/{snapshot-L2G56RPL.js → snapshot-3IYB67D4.js} +1 -1
  43. package/dist/{status-77M3SDIF.js → status-DB3KNLW3.js} +1 -1
  44. package/dist/{summary-LXLHFRN7.js → summary-PYTEIJ4U.js} +1 -1
  45. package/dist/{team-NSP6PMPS.js → team-PDK64JXI.js} +1 -1
  46. package/dist/{test-BQJMS4Y2.js → test-WLEPZQFC.js} +1 -1
  47. package/dist/{tools-BZUAEUSQ.js → tools-5ITPEPSV.js} +1 -1
  48. package/dist/{validate-VZXTJHGO.js → validate-BB6LRWIY.js} +1 -1
  49. package/dist/workspace-VMSPYIBV.js +2 -0
  50. package/package.json +2 -1
  51. package/templates/paradigm/specs/symbols.md +4 -2
  52. package/dist/chunk-3TR6LLXP.js +0 -111
  53. package/dist/chunk-3VF3CMCF.js +0 -521
  54. package/dist/chunk-J6KWGCHN.js +0 -24
  55. package/dist/chunk-QT2LKB3P.js +0 -7
  56. package/dist/chunk-SHD27BQX.js +0 -6
  57. package/dist/compliance-WJINB5DM.js +0 -6
  58. package/dist/dist-R3RWD35F.js +0 -2
  59. package/dist/dist-VXCZWVVJ.js +0 -2
  60. package/dist/doctor-QJ47XAUP.js +0 -2
  61. package/dist/init-HIBRSVUB.js +0 -2
  62. package/dist/portal-check-Z3OCQEQR.js +0 -8
  63. package/dist/portal-compliance-4MG5F2GI.js +0 -2
  64. package/dist/workspace-MKSQN7B2.js +0 -2
@@ -1,24 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a as a$3}from'./chunk-TYWB5IQJ.js';import {b,a as a$1}from'./chunk-ORDKEGII.js';import {e}from'./chunk-AO7ZSRME.js';import {a}from'./chunk-FYDRENK7.js';import {b as b$1}from'./chunk-EKZDFEJW.js';import {a as a$2,b as b$2}from'./chunk-SHD27BQX.js';import {o,t,x}from'./chunk-T6IDXUUA.js';import'minimatch';import*as w from'fs';import*as C from'path';import*as F from'js-yaml';import {spawn}from'child_process';var ee=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],te=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],se=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],re=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],ne=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],oe=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,Y={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function ie(f){let s=f.match(oe)||[];return [...new Set(s)]}function $(f,s){let e=f.toLowerCase();return s.filter(t=>e.includes(t.toLowerCase()))}function ae(f,s,e,t){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let o=f.split(/\s+/).length;o>=100?n+=2:o>=50&&(n+=1);let r=new Set(e.map(a=>a[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(a=>a.startsWith("^"))&&(n+=1),e.some(a=>a.startsWith("$"))&&(n+=1),s==="feature"&&(n+=1),s==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function le(f,s,e){if($(f,ne).length>0||s.some(n=>n.startsWith("^")))return true;return false}function K(f,s){let e=ie(f),t=$(f,ee),n=$(f,te),o=$(f,se),r=$(f,re),a,i;t.length>0&&o.length===0&&r.length===0?(a="analysis",i=t):n.length>0&&o.length===0?(a="documentation",i=n):o.length>0?(a="bugfix",i=o):r.length>0?(a="refactor",i=r):(a="feature",i=[]);let l=Y[a],g=le(f,e),c=[...l.agents];g&&!c.includes("security")&&(c=["security",...c]);let p=ae(f,a,e),h={...l.costMultiplier};return p==="high"?(h.min*=1.2,h.max*=1.3):p==="low"&&(h.min*=.8,h.max*=.9),g&&!l.agents.includes("security")&&(h.min+=.15,h.max+=.2),{type:a,complexity:p,recommendedAgents:c,securityRequired:g,costMultiplier:h,matchedKeywords:i,symbols:e}}function B(f,s){let e=Y[s.type];return f==="security"&&s.securityRequired?"opus":e.models[f]||"sonnet"}var ce=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ue=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],de=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function V(f,s,e$1){let t$1=f.toLowerCase(),n=f.match(ce)||[],o=[...new Set(n)],r=o.map(d=>{let u=t(e$1,d),y=u.length>0?u[0]:null;return {symbol:d,exists:!!y,type:y?.type,description:y?.description}}),a=r.filter(d=>d.exists).map(d=>{let u=x(e$1,d.symbol),y=new Set;for(let b of u){let S=x(e$1,b.symbol);for(let O of S)O.symbol!==d.symbol&&!u.find(v=>v.symbol===O.symbol)&&y.add(O.symbol);}let k=u.length+y.size,m="low";return k>10?m="high":k>3&&(m="medium"),{symbol:d.symbol,directDependents:u.length,indirectDependents:y.size,impact:m}}),i=a$2(s),l={exists:!!i,gateCount:i?b$2(i).length:0,gates:i?b$2(i).map(d=>`^${d}`):[],routeCount:i?.routes?Object.keys(i.routes).length:0},g=de.some(d=>t$1.includes(d)),c=e(s),p=c?a$3(f,c.agents).map(d=>({name:d.name,confidence:d.confidence,reason:d.reason})):[],h=[];return r.some(d=>d.exists)&&h.push("ripple-analysis"),g&&h.push("portal-compliance"),o.some(d=>d.startsWith("^"))&&h.push("gate-validation"),o.some(d=>d.startsWith("!"))&&h.push("signal-registration"),h.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:a,portalStatus:l,taskAddsRoutes:g,suggestedAgents:p,requiredChecks:h}}function H(f,s,e,t$1){let n=[],o=a$2(e),r=o?b$2(o):[],a=o?.routes?Object.keys(o.routes):[];for(let p of f){let h=C.isAbsolute(p)?p:C.join(e,p);if(!w.existsSync(h))continue;let d;try{d=w.readFileSync(h,"utf-8");}catch{continue}for(let u of ue){u.lastIndex=0;let y;for(;(y=u.exec(d))!==null;){let k=y[2]||y[0];k&&k.startsWith("/")&&(!a.some(b=>b.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===k)&&o?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${k}" found in ${C.relative(e,h)} but not declared in portal.yaml`,file:C.relative(e,h),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!o&&k.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${k}" found but no portal.yaml exists`,file:C.relative(e,h),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of s)t(t$1,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of s)if(p.startsWith("^")){let h=p.slice(1);r.includes(h)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}f.length>=5&&s.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${f.length} files, ${s.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let i=n.filter(p=>p.severity==="error").length,l=n.filter(p=>p.severity==="warning").length,g=4,c="pass";return i>0?c="violations":l>0&&(c="warnings"),{status:c,violations:n,summary:{totalChecks:g,passed:g-(i>0?1:0)-(l>0?1:0),warnings:l,errors:i},blocksCompletion:i>0}}var pe={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},he=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function me(f,s){let e=f.toLowerCase(),t=he.some(r=>e.includes(r.toLowerCase())),n=f.includes("^"),o=false;return t||n||o}var ye=["rename","refactor","migrate","restructure","move","reorganize"];function be(f){let s=f.toLowerCase();return ye.some(e=>s.includes(e))}var E=class{spawner;auditLogger;rootDir;constructor(s){this.rootDir=s,this.spawner=new b(s),this.auditLogger=new a(s);}async initialize(){await this.spawner.initialize();}async orchestrate(s,e={}){let t=e.mode||"faceted",n=Date.now(),o$1=this.generateOrchestrationId(),r={success:false,mode:t,orchestrationId:o$1,task:s,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let a;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:l}=await import('./dist-3ZCH25SG.js'),g=await l(this.rootDir),c=o(g);a=V(s,this.rootDir,c);}catch{}if(t==="solo"){let l=await this.runSoloMode(s,e);r.agentsSpawned=1,r.agentResults=[l],r.success=l.success,l.relay&&(r.totalTokens=l.relay.metrics.tokens_used,r.totalCost=b$1(r.totalTokens,e.orchestratorModel||"opus"));}else {let l=await this.runFacetedMode(s,e);r.agentsSpawned=l.results.length,r.agentResults=l.results,r.totalTokens=l.totalTokens,r.totalCost=l.totalCost,r.success=l.success,r.parallelBuilderStats=l.parallelBuilderStats;}if(e.pmGovernance?.enabled&&a)try{let{aggregateFromDirectory:l}=await import('./dist-3ZCH25SG.js'),g=await l(this.rootDir),c=o(g),p=[],h=[];for(let u of r.agentResults)u.relay?.outputs?.artifacts&&p.push(...u.relay.outputs.artifacts.map(y=>y.path));for(let u of a.affectedSymbols)h.push(u.symbol);let d=H(p,h,this.rootDir,c);r.complianceReport={preflight:a,postflight:d},e.pmGovernance.blockOnViolations&&d.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:a};}r.duration_ms=Date.now()-n;let i=this.auditLogger.startOrchestration(o$1,s,t);return i.completed=new Date().toISOString(),i.status=r.success?"success":"failed",i.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(i),r.log=i,r}catch(a){return r.error=a instanceof Error?a.message:String(a),r.duration_ms=Date.now()-n,r}}async compare(s,e={}){let t=await this.orchestrate(s,{...e,mode:"solo"}),n=await this.orchestrate(s,{...e,mode:"faceted"}),o=t.totalTokens.total-n.totalTokens.total,r=t.totalCost-n.totalCost,a=t.duration_ms-n.duration_ms,i="tie";return n.success&&!t.success?i="faceted":t.success&&!n.success?i="solo":n.totalCost<t.totalCost*.8?i="faceted":t.totalCost<n.totalCost*.8&&(i="solo"),{solo:t,faceted:n,comparison:{winner:i,tokensSaved:o,costDiff:r,timeDiff:a,soloSucceeded:t.success,facetedSucceeded:n.success}}}async runSoloMode(s,e$1){let n=e(this.rootDir)?.team.default_agent||"architect",o=e$1.orchestratorModel||"opus",r={model:o,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?i=>e$1.onMessage("solo",i):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",s,o);let a=await this.spawner.spawn(n,s,r);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",a,o),a}async runFacetedMode(s,e$1){let t=e(this.rootDir);if(!t)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let n="";if(be(s)){let d=a$1(s);if(d.length>0){let u=[];u.push(`## Auto-Ripple Analysis
3
- `),u.push("The following symbols are affected by this refactoring:"),u.push("");for(let y of d.slice(0,5))u.push(`- **${y}**: Check dependencies before renaming/moving`);u.push(""),u.push("**Recommendation:** Run `paradigm_ripple` for each symbol before making changes."),n=u.join(`
4
- `);}}let o=this.planAgentSequence(s,t.agents),r=this.groupByStage(o),a=[],i={input:0,output:0,total:0},l=0,g=new Map,c=true,p,h=Array.from(r.keys()).sort((d,u)=>d-u);for(let d of h){let u=r.get(d)||[];if(u.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let m=u.map(S=>S.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${d}: Spawn ${m}${u.length>1?" (parallel)":""}`)){c=false;break}}let y=u.map(async m=>{let b=e$1.agentBudgets?.[m.agent]?.maxTokens?"haiku":m.model||pe[m.agent]||"sonnet",S="";if(m.dependsOn.length>0){let R=m.dependsOn.map(I=>g.get(I)).filter(Boolean);R.length>0&&(S=R.join(`
5
-
6
- ---
7
-
8
- `));}let O=S;m.agent==="architect"&&n&&(O=n+(S?`
9
-
10
- ---
11
-
12
- `+S:""));let v=O?`${m.subtask}
13
-
14
- ## Context from previous agents:
15
- ${O}`:m.subtask,A={model:b,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.agentBudgets?.[m.agent]||e$1.budget,onMessage:e$1.onMessage?R=>e$1.onMessage(m.agent,R):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart(m.agent,m.subtask,b);let P=await this.spawner.spawn(m.agent,v,A);return e$1.onAgentComplete&&e$1.onAgentComplete(m.agent,P,b),{step:m,result:P,model:b}}),k=await Promise.all(y);for(let{step:m,result:b,model:S}of k){if(a.push(b),b.relay){i.input+=b.relay.metrics.tokens_used.input,i.output+=b.relay.metrics.tokens_used.output,i.total+=b.relay.metrics.tokens_used.total,l+=b$1(b.relay.metrics.tokens_used,S);let O=b.relay.handoff?.context||`${m.agent} completed: ${b.relay.outputs.decisions.join(", ")||"task done"}`;if(g.set(m.agent,O),m.agent==="architect"&&b.relay){let v=this.extractFilePlanFromRelay(b);if(v&&v.length>0){let A=this.planBuilderStages(v);if(A.hasFilePlan&&A.totalBuilders>1){let P=await this.runParallelBuilders(A,g.get("architect")||"",e$1);a.push(...P.results),i.input+=P.totalTokens.input,i.output+=P.totalTokens.output,i.total+=P.totalTokens.total,l+=P.totalCost,P.success||(c=false),p={usedFilePlan:true,totalSubPhases:A.stages.length,totalParallelBuilders:A.totalBuilders,filesCreated:A.totalFiles};for(let[R,I]of r){let X=I.filter(Q=>Q.agent!=="builder");r.set(R,X);}}}}}!b.success&&m.required&&(c=false);}if(!c||e$1.checkpoints?.afterAgentComplete&&e$1.onCheckpoint&&!await e$1.onCheckpoint(`Stage ${d} completed. Continue to next stage?`))break}return {success:c,results:a,totalTokens:i,totalCost:l,parallelBuilderStats:p}}extractFilePlanFromRelay(s){if(!s.relay)return;let e=s.relay.handoff?.context||"";if(e.includes("filePlan:"))return this.parseFilePlanFromText(e)}parseFilePlanFromText(s){let e=[],t=s.match(/filePlan:\s*\n([\s\S]*?)(?=\n[a-z_]+:|$)/);if(!t)return;let o=t[1].split(`
16
- `),r=null,a=false,i={};for(let l of o){let g=l.trim();if(!(!g||g.startsWith("#"))){if(g.startsWith("- group:")){r&&(i.path&&(r.files.push({path:i.path,description:i.description||""}),i={}),e.push(r)),r={group:g.split(":")[1].trim(),subPhase:0,files:[]},a=false;continue}if(r){if(g.startsWith("subPhase:")){r.subPhase=parseInt(g.split(":")[1].trim(),10)||0;continue}if(g==="files:"){a=true;continue}if(a){if(g.startsWith("- path:")){i.path&&r.files.push({path:i.path,description:i.description||""}),i={path:g.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"")};continue}if(g.startsWith("description:")){i.description=g.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"");continue}}}}}return i.path&&r&&r.files.push({path:i.path,description:i.description||""}),r&&e.push(r),e.length>0?e:void 0}planAgentSequence(s,e){let t=a$1(s),n=s.toLowerCase(),o=K(s),r=[],a=me(s);if(o.type==="analysis")return e.architect&&r.push({agent:"architect",subtask:`Analyze and recommend: ${s}`,required:true,stage:0,dependsOn:[],model:"opus"}),r;if(o.type==="documentation")return e.architect&&r.push({agent:"architect",subtask:`Document: ${s}`,required:true,stage:0,dependsOn:[],model:"sonnet"}),r;let i=n.includes("design")||n.includes("architect")||n.includes("plan")||n.includes("spec"),l=a||n.includes("auth")||n.includes("security")||n.includes("gate")||t.some(u=>u.startsWith("^"));if(i&&e.architect&&r.push({agent:"architect",subtask:`Design and specify: ${s}`,required:true,stage:0,dependsOn:[],model:"opus"}),l&&e.security&&r.push({agent:"security",subtask:`Review security aspects of: ${s}`,required:a,stage:0,dependsOn:[],model:"opus"}),(n.includes("build")||n.includes("implement")||n.includes("create")||n.includes("add")||n.includes("fix"))&&e.builder){let u=i&&e.architect?["architect"]:[];r.push({agent:"builder",subtask:`Implement: ${s}`,required:true,stage:u.length>0?1:0,dependsOn:u,model:"haiku"});}let c=n.includes("review")||n.includes("check"),p=n.includes("test")||n.includes("verify")||n.includes("validate"),h=r.some(u=>u.agent==="builder"),d=h?2:i?1:0;if(c&&e.reviewer&&r.push({agent:"reviewer",subtask:`Review: ${s}`,required:false,stage:d,dependsOn:h?["builder"]:[],model:"sonnet"}),p&&e.tester&&r.push({agent:"tester",subtask:`Test and validate: ${s}`,required:false,stage:d,dependsOn:h?["builder"]:[],model:"haiku"}),r.length===0){let u=o.recommendedAgents;if(u.includes("architect")&&e.architect&&r.push({agent:"architect",subtask:`Design: ${s}`,required:true,stage:0,dependsOn:[],model:B("architect",o)}),(u.includes("security")||a)&&e.security&&r.push({agent:"security",subtask:`Security review: ${s}`,required:a,stage:0,dependsOn:[],model:"opus"}),u.includes("builder")&&e.builder){let y=r.length>0;r.push({agent:"builder",subtask:`Implement: ${s}`,required:true,stage:y?1:0,dependsOn:r.filter(k=>k.stage===0).map(k=>k.agent),model:B("builder",o)});}if(u.includes("tester")&&e.tester){let y=r.find(k=>k.agent==="builder")?.stage??0;r.push({agent:"tester",subtask:`Test: ${s}`,required:false,stage:y+1,dependsOn:e.builder?["builder"]:[],model:B("tester",o)});}}return r.sort((u,y)=>u.stage-y.stage)}groupByStage(s){let e=new Map;for(let t of s){let n=e.get(t.stage)||[];n.push({agent:t.agent,subtask:t.subtask,required:t.required,dependsOn:t.dependsOn}),e.set(t.stage,n);}return e}generateOrchestrationId(){let s=new Date().toISOString().slice(0,10),e=Math.random().toString(36).substring(2,8);return `orch-${s}-${e}`}planBuilderStages(s){if(!s||s.length===0)return {hasFilePlan:false,stages:[{subPhase:0,builders:[{agent:"builder",group:"all",files:[],availableFiles:[]}]}],totalFiles:0,totalBuilders:1};let e=new Map;for(let i of s){let l=e.get(i.subPhase)||[];l.push(i),e.set(i.subPhase,l);}let t=[],n=[...e.keys()].sort((i,l)=>i-l),o=[],r=0,a=0;for(let i of n){let l=e.get(i),g=[];for(let c=0;c<l.length;c++){let p=l[c];a+=p.files.length,r++,g.push({agent:`builder-${i}-${c}`,group:p.group,files:p.files,availableFiles:[...o]});}t.push({subPhase:i,builders:g});for(let c of l)for(let p of c.files)o.push(p.path);}return {hasFilePlan:true,stages:t,totalFiles:a,totalBuilders:r}}buildParallelBuilderPrompt(s,e,t,n){let o=[];o.push(`You are a BUILDER agent responsible for implementing the **${n}** group.`),o.push(""),o.push("## Your Assignment"),o.push(""),o.push("### Files to Create:");for(let r of s)o.push(`- \`${r.path}\`: ${r.description}`);if(o.push(""),e.length>0){o.push("### Available Files (already created):"),o.push("These files exist and you can import from them:");for(let r of e)o.push(`- \`${r}\``);o.push("");}return t&&(o.push("### Context from Architect:"),o.push(t),o.push("")),o.push("### Instructions:"),o.push("1. Create ONLY the files assigned to you"),o.push("2. You can import from available files (already created)"),o.push("3. Follow existing patterns in the codebase"),o.push("4. Use the Paradigm logger (not console.log)"),o.push("5. End with the standard Agent Relay block"),o.join(`
17
- `)}async runParallelBuilders(s,e,t){let n=[],o={input:0,output:0,total:0},r=0,a=true;for(let i of s.stages){if(t.checkpoints?.beforeAgentSpawn&&t.onCheckpoint){let c=i.builders.map(h=>h.group).join(", ");if(!await t.onCheckpoint(`Builder Sub-phase ${i.subPhase}: ${c}${i.builders.length>1?" (parallel)":""}`)){a=false;break}}let l=i.builders.map(async c=>{let p=this.buildParallelBuilderPrompt(c.files,c.availableFiles,e,c.group),h={model:"haiku",workingDirectory:t.workingDirectory||this.rootDir,mcpServerPath:t.mcpServerPath,budget:t.budget,onMessage:t.onMessage?u=>t.onMessage(c.agent,u):void 0,onCheckpoint:t.onCheckpoint};t.onAgentStart&&t.onAgentStart(c.agent,`Implement ${c.group}`,"haiku");let d=await this.spawner.spawn("builder",p,h);return t.onAgentComplete&&t.onAgentComplete(c.agent,d,"haiku"),{builder:c,result:d}}),g=await Promise.all(l);for(let{result:c}of g)n.push(c),c.relay&&(o.input+=c.relay.metrics.tokens_used.input,o.output+=c.relay.metrics.tokens_used.output,o.total+=c.relay.metrics.tokens_used.total,r+=b$1(c.relay.metrics.tokens_used,"haiku")),c.success||(a=false);if(!a||t.checkpoints?.afterAgentComplete&&t.onCheckpoint&&!await t.onCheckpoint(`Sub-phase ${i.subPhase} complete. Continue to next sub-phase?`))break}return {success:a,results:n,totalTokens:o,totalCost:r}}};var J=class{rootDir;orchestrationsDir;constructor(s){this.rootDir=s,this.orchestrationsDir=C.join(s,".paradigm","orchestrations"),this.ensureOrchestrationDir();}async startBackground(s,e={}){let t=this.generateId(),n=C.join(this.orchestrationsDir,`${t}.output`),o=C.join(this.orchestrationsDir,`${t}.log`),r={id:t,task:s,status:"pending",mode:e.mode||"faceted",created:new Date().toISOString(),outputFile:n,logFile:o,artifacts:[]};return this.saveOrchestration(r),this.spawnOrchestration(t,s,e),r}getOrchestration(s){let e=C.join(this.orchestrationsDir,`${s}.yaml`);if(!w.existsSync(e))return null;try{let t=w.readFileSync(e,"utf-8");return F.load(t)}catch{return null}}listOrchestrations(s={}){let e=w.readdirSync(this.orchestrationsDir).filter(n=>n.endsWith(".yaml")&&!n.includes("output")&&!n.includes("log")).sort().reverse(),t=[];for(let n of e){if(s.limit&&t.length>=s.limit)break;let o=C.join(this.orchestrationsDir,n);try{let r=w.readFileSync(o,"utf-8"),a=F.load(r);if(s.status&&!(Array.isArray(s.status)?s.status:[s.status]).includes(a.status))continue;t.push(a);}catch{}}return t}getRunning(){return this.listOrchestrations({status:"running"})}getOutput(s,e={}){let t=this.getOrchestration(s);if(!t||!w.existsSync(t.outputFile))return "";let n=w.readFileSync(t.outputFile,"utf-8");return e.lines?n.split(`
18
- `).slice(-e.lines).join(`
19
- `):n}async accept(s,e={}){let t=this.getOrchestration(s);if(!t)return false;if(t.status!=="completed")throw new Error(`Cannot accept orchestration in '${t.status}' status`);return t.status="accepted",this.saveOrchestration(t),true}async reject(s,e={}){let t=this.getOrchestration(s);if(!t)return false;if(t.status!=="completed")throw new Error(`Cannot reject orchestration in '${t.status}' status`);if(t.status="rejected",t.error=e.reason,this.saveOrchestration(t),e.cleanup&&t.artifacts.length>0){for(let n of t.artifacts)if(n.action==="created"){let o=C.join(this.rootDir,n.path);w.existsSync(o)&&w.unlinkSync(o);}}return true}async getDiff(s){let e=this.getOrchestration(s);if(!e)return "";if(e.artifacts.length===0)return "No file changes in this orchestration.";let t=[];t.push(`Orchestration: ${s}`),t.push(`Task: ${e.task}`),t.push(`Status: ${e.status}`),t.push(""),t.push("Files:");for(let n of e.artifacts){let o=n.action==="created"?"+":n.action==="modified"?"~":"-";t.push(` ${o} ${n.path}`);}return t.join(`
20
- `)}markComplete(s,e){let t=this.getOrchestration(s);if(t){t.status=e.success?"completed":"failed",t.completed=new Date().toISOString(),t.result=e,t.parallelBuilderStats=e.parallelBuilderStats;for(let n of e.agentResults)if(n.relay?.outputs.artifacts)for(let o of n.relay.outputs.artifacts)t.artifacts.push(o);this.saveOrchestration(t);}}async notify(s,e=["bell"]){let t=this.getOrchestration(s);if(t)for(let n of e)switch(n){case "bell":process.stdout.write("\x07");break;case "desktop":try{process.platform==="darwin"?spawn("osascript",["-e",`display notification "Orchestration ${t.status}: ${t.task.slice(0,50)}" with title "Paradigm"`]):spawn("notify-send",["Paradigm",`Orchestration ${t.status}: ${t.task.slice(0,50)}`]);}catch{}break;case "file":let o=C.join(this.orchestrationsDir,`${s}.status`);w.writeFileSync(o,JSON.stringify({id:s,status:t.status,completed:t.completed,task:t.task}));break;}}ensureOrchestrationDir(){w.existsSync(this.orchestrationsDir)||w.mkdirSync(this.orchestrationsDir,{recursive:true});}generateId(){let s=new Date().toISOString().slice(0,10),e=Date.now().toString(36),t=Math.random().toString(36).substring(2,6);return `orch-${s}-${e}-${t}`}saveOrchestration(s){let e=C.join(this.orchestrationsDir,`${s.id}.yaml`);w.writeFileSync(e,F.dump(s));}spawnOrchestration(s,e,t){let n=this.getOrchestration(s);n&&(n.status="running",n.started=new Date().toISOString(),this.saveOrchestration(n)),(async()=>{try{let o=new E(this.rootDir);await o.initialize();let r=w.createWriteStream(n.outputFile,{flags:"a"}),a=await o.orchestrate(e,{...t,onMessage:(i,l)=>{l.type==="text"&&r.write(`[${i}] ${l.content}
21
- `),t.onMessage?.(i,l);},onAgentStart:(i,l,g)=>{r.write(`
22
- \u25B6 ${i}: ${l}
23
- `),t.onAgentStart?.(i,l,g);},onAgentComplete:(i,l,g)=>{let c=l.success?"\u2713":"\u2717";r.write(`${c} ${i} completed
24
- `),t.onAgentComplete?.(i,l,g);}});r.end(),this.markComplete(s,a),t.notify&&await this.notify(s,t.notifyMethods||["bell"]);}catch(o){let r=this.getOrchestration(s);r&&(r.status="failed",r.error=o instanceof Error?o.message:String(o),r.completed=new Date().toISOString(),this.saveOrchestration(r));}})();}};export{E as a,J as b};
@@ -1,7 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as d from'fs';import*as r from'path';import*as p from'js-yaml';import {glob}from'glob';var w={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function F(e){let t=r.resolve(e),o=r.dirname(t);if(!d.existsSync(t))throw new Error(`Gate config not found: ${t}`);let n=d.readFileSync(t,"utf8"),s=p.load(n);if(!s.version)throw new Error('Gate config missing required "version" field');let i=[],a=s,l=s.gates||a.portals;if(l)for(let[f,c]of Object.entries(l))i.push(u(f,c));if(s.include)for(let f of s.include){let c=r.join(o,f),m=await glob(c.replace(/\\/g,"/"));for(let y of m){let $=await v(y);i.push(...$);}}let h=[];if(s.flows)for(let[f,c]of Object.entries(s.flows))h.push(D(f,c));return {version:s.version,gates:i,flows:h,settings:{dev:{...w,...s.settings?.dev}}}}async function v(e){let t=d.readFileSync(e,"utf8"),o=p.load(t);if(o.id)return [u(o.id,o)];if(o.gates){let n=[];for(let[s,i]of Object.entries(o.gates))n.push(u(s,i));return n}return []}function u(e,t){let o=[];if(t.locks)for(let s of t.locks)o.push(z(s));let n=[];if(t.prizes)for(let s of t.prizes)n.push(k(s));return {id:e,description:t.description,locks:o,prizes:n,position:t.position}}function z(e){let t=e,o=[];if(t.keys){for(let n of t.keys)if(typeof n=="string")o.push({expression:n});else if(n.expression){let s=n;o.push({expression:s.expression,description:s.description});}}return {id:t.id,description:t.description,keys:o,mode:t.mode||"all"}}function k(e){let t=e;return {id:t.id,oneTime:t.oneTime??false,metadata:t.metadata}}function D(e,t){return {id:e,description:t.description,gates:t.gates||[],forkable:t.forkable}}function C(e){let t={version:e.version,gates:{},flows:{},settings:{dev:e.settings.dev}};for(let o of e.gates){let{id:n,...s}=o;t.gates[n]=s;}for(let o of e.flows){let{id:n,...s}=o;t.flows[n]=s;}return p.dump(t,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function S(){return p.dump({version:"1.0.0",gates:{"example-gate":{description:"An example gate to get you started",locks:[{id:"example-lock",description:"Requires user to be authenticated",keys:[{expression:"user.isAuthenticated === true"}]}],prizes:[{id:"example-prize",oneTime:true,metadata:{event:"first_access"}}]}},flows:{"example-flow":{description:"An example user journey",gates:["example-gate"]}},settings:{dev:{visualizerPort:42195,watcherPort:42196,autoConnect:true}}},{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}async function P(e){let t=r.resolve(e);return await glob("**/portal.yaml",{cwd:t,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}function j(e){let t=[];e.version||t.push({type:"error",message:'Missing required "version" field',path:"version"});let o=new Set;for(let n of e.gates)b(n,o,t),o.add(n.id);for(let n of e.flows)G(n,o,t);return {valid:t.filter(n=>n.type==="error").length===0,issues:t}}function b(e,t,o){let n=`gates.${e.id}`;t.has(e.id)&&o.push({type:"error",message:`Duplicate gate ID: "${e.id}"`,path:n}),/^[a-z][a-z0-9-]*$/.test(e.id)||o.push({type:"warning",message:`Gate ID "${e.id}" should use kebab-case (e.g., "my-gate")`,path:n});let s=new Set;for(let a of e.locks)x(a,s,`${n}.locks`,o),s.add(a.id);let i=new Set;for(let a of e.prizes)i.has(a.id)&&o.push({type:"error",message:`Duplicate prize ID "${a.id}" in gate "${e.id}"`,path:`${n}.prizes`}),i.add(a.id),/^[a-z][a-z0-9-]*$/.test(a.id)||o.push({type:"warning",message:`Prize ID "${a.id}" should use kebab-case`,path:`${n}.prizes`});e.locks.length===0&&o.push({type:"warning",message:`Gate "${e.id}" has no locks - any entity can pass through`,path:n});}function x(e,t,o,n){let s=`${o}.${e.id}`;t.has(e.id)&&n.push({type:"error",message:`Duplicate lock ID: "${e.id}"`,path:s}),/^[a-z][a-z0-9-]*$/.test(e.id)||n.push({type:"warning",message:`Lock ID "${e.id}" should use kebab-case`,path:s}),e.keys.length===0&&n.push({type:"error",message:`Lock "${e.id}" has no keys - it can never be opened`,path:s});for(let i of e.keys)(!i.expression||i.expression.trim()==="")&&n.push({type:"error",message:`Key in lock "${e.id}" has empty expression`,path:`${s}.keys`}),i.expression.includes("==")&&!i.expression.includes("===")&&n.push({type:"warning",message:'Key expression uses "==" instead of "===" - consider using strict equality',path:`${s}.keys`});e.mode&&!["all","any"].includes(e.mode)&&n.push({type:"error",message:`Invalid lock mode "${e.mode}" - must be "all" or "any"`,path:s});}function G(e,t,o){let n=`flows.${e.id}`;/^[a-z][a-z0-9-]*$/.test(e.id)||o.push({type:"warning",message:`Flow ID "${e.id}" should use kebab-case`,path:n});for(let i of e.gates)t.has(i)||o.push({type:"error",message:`Flow "${e.id}" references unknown gate "${i}"`,path:`${n}.gates`});e.gates.length===0&&o.push({type:"warning",message:`Flow "${e.id}" has no gates`,path:n});let s=new Set;for(let i of e.gates)s.has(i)&&o.push({type:"warning",message:`Flow "${e.id}" contains duplicate gate "${i}"`,path:`${n}.gates`}),s.add(i);}function A(e){if(e.valid&&e.issues.length===0)return "\u2705 Configuration is valid";let t=[],o=e.issues.filter(s=>s.type==="error"),n=e.issues.filter(s=>s.type==="warning");if(o.length>0){t.push(`
3
- \u274C ${o.length} error(s):`);for(let s of o)t.push(` \u2022 ${s.message}${s.path?` (${s.path})`:""}`);}if(n.length>0){t.push(`
4
- \u26A0\uFE0F ${n.length} warning(s):`);for(let s of n)t.push(` \u2022 ${s.message}${s.path?` (${s.path})`:""}`);}return e.valid?t.push(`
5
- \u2705 Configuration is valid (with warnings)`):t.push(`
6
- \u274C Configuration is invalid`),t.join(`
7
- `)}export{F as a,v as b,C as c,S as d,P as e,j as f,A as g};
@@ -1,6 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as m from'fs';import*as h from'path';import*as R from'js-yaml';import {execFileSync}from'child_process';var G=["node_modules",".git","dist","build","coverage",".paradigm","vendor","__pycache__",".next","target"];function S(e){let t=h.join(e,"portal.yaml");if(!m.existsSync(t))return null;try{let n=m.readFileSync(t,"utf-8");return R.load(n)}catch{return null}}function C(e){let t=new Set;if(e.gates)for(let n of Object.keys(e.gates)){let s=n.startsWith("^")?n.slice(1):n;t.add(s);}if(e.routes)for(let n of Object.values(e.routes)){let s=Array.isArray(n)?n:n.gates||[];for(let o of s){let a=o.startsWith("^")?o.slice(1):o;t.add(a);}}return Array.from(t)}function B(e){let t=new Set;if(e.routes)for(let n of Object.values(e.routes)){let s=Array.isArray(n)?n:n.gates||[];for(let o of s){let a=o.startsWith("^")?o.slice(1):o;t.add(a);}}return t}function E(e,t){let n={encoding:"utf-8",maxBuffer:10485760,stdio:["ignore","pipe","pipe"]};try{let i=["-n","--no-ignore-vcs",...G.flatMap(u=>["--glob",`!${u}/**`]),"--engine","auto",t,e];return execFileSync("rg",i,n)}catch{}let o=["-rn",...G.map(a=>`--exclude-dir=${a}`),"-E",t,"--",e];try{return execFileSync("grep",o,n)}catch(a){return a?.code===1||a?.status===1,""}}var P=["**/.purpose","**/portal.yaml","**/.paradigm/**/*.yaml","**/.paradigm/**/*.yml"];function x(e){let t=[];for(let o of P){h.join(e,o);let i;try{i=execFileSync("find",[e,"-path","*/node_modules","-prune","-o","-path","*/.git","-prune","-o","(","-name",".purpose","-o","-name","portal.yaml",")","-print"],{encoding:"utf-8",maxBuffer:5242880}).split(`
3
- `).filter(Boolean);}catch{i=[];}for(let u of i)try{let p=m.readFileSync(u,"utf-8").split(`
4
- `);for(let l=0;l<p.length;l++){let d=p[l],g=d.matchAll(/\^([a-z][a-z0-9-]+)/g);for(let c of g)t.push({gate:c[1],file:h.relative(e,u),line:l+1,context:d.trim().slice(0,100),matchType:"symbol"});}}catch{}}let s=[{pattern:`checkGate\\s*\\(['"]([^'"]+)['"]`,type:"function"},{pattern:`requireGate\\s*\\(['"]([^'"]+)['"]`,type:"function"},{pattern:`@Gate\\s*\\(['"]?([^'"\\)]+)['"]?\\)`,type:"function"}];for(let{pattern:o,type:a}of s){let i=E(e,o);for(let u of i.split(`
5
- `).filter(Boolean)){let f=u.match(/^(.+?):(\d+):(.*)$/);if(f){let[,p,l,d]=f,g=d.match(new RegExp(o));if(g&&g[1]){let c=g[1].startsWith("^")?g[1].slice(1):g[1];t.push({gate:c,file:h.relative(e,p),line:parseInt(l,10),context:d.trim().slice(0,100),matchType:a});}}}}return t}function $(e){return [...new Set(e.map(t=>t.gate))]}async function w(e){let t=S(e);if(!t){let r=x(e),U=$(r);return U.length===0?{status:"compliant",declaredButUnused:[],routeAttachedUnused:[],orphanUnused:[],usedButUndeclared:[],properlyDeclared:[],suggestions:["No portal.yaml found, and no gate references detected in code."],references:[]}:{status:"violations",declaredButUnused:[],routeAttachedUnused:[],orphanUnused:[],usedButUndeclared:U,properlyDeclared:[],suggestions:["Gate references found in code but no portal.yaml exists.","Create a portal.yaml file to declare these gates:",...U.map(b=>` - ^${b}`),"","Run: paradigm portal init"],references:r}}let n=C(t),s=B(t),o=x(e),a=$(o),i=new Set(n),u=new Set(a),f=n.filter(r=>!u.has(r)),p=f.filter(r=>s.has(r)),l=f.filter(r=>!s.has(r)),d=a.filter(r=>!i.has(r)),g=n.filter(r=>u.has(r)),c=[];if(p.length>0){c.push("Gates documented on routes but no checkGate/requireGate in code:");for(let r of p)c.push(` - ^${r} (documented on routes; if enforced by middleware, this may be intentional)`);c.push("");}if(l.length>0){c.push("Orphan gates (declared but never on a route or in code):");for(let r of l)c.push(` - ^${r} (add to a route or remove from portal.yaml)`);c.push("");}if(d.length>0){c.push("Gates used in code but not declared in portal.yaml:");for(let r of d)c.push(` - ^${r} (add to portal.yaml with proper definition)`);c.push("");}let y="compliant";return d.length>0?y="violations":f.length>0&&(y="warnings"),{status:y,declaredButUnused:f,routeAttachedUnused:p,orphanUnused:l,usedButUndeclared:d,properlyDeclared:g,suggestions:c,references:o}}function _(e){let t=[],n=e.status==="compliant"?"\u2713":e.status==="warnings"?"\u26A0":"\u2717";if(t.push(`Portal Compliance: ${n} ${e.status.toUpperCase()}`),t.push(""),t.push(`Properly Declared: ${e.properlyDeclared.length}`),e.routeAttachedUnused.length>0&&t.push(`Route-Attached, No Code: ${e.routeAttachedUnused.length}`),e.orphanUnused.length>0&&t.push(`Orphan Gates: ${e.orphanUnused.length}`),e.usedButUndeclared.length>0&&t.push(`Used but Undeclared: ${e.usedButUndeclared.length}`),t.push(""),e.properlyDeclared.length>0){t.push("Gates in Use:");for(let s of e.properlyDeclared)t.push(` \u2713 ^${s}`);t.push("");}if(e.routeAttachedUnused.length>0){t.push("Route-Attached (no checkGate/requireGate in code):");for(let s of e.routeAttachedUnused)t.push(` \u26A0 ^${s}`);t.push("");}if(e.orphanUnused.length>0){t.push("Orphan Gates (declared but never on route or in code):");for(let s of e.orphanUnused)t.push(` \u26A0 ^${s}`);t.push("");}if(e.usedButUndeclared.length>0){t.push("Undeclared Gates (used but not in portal.yaml):");for(let s of e.usedButUndeclared){t.push(` \u2717 ^${s}`);let o=e.references.filter(a=>a.gate===s).slice(0,3);for(let a of o)t.push(` at ${a.file}:${a.line}`);}t.push("");}if(e.suggestions.length>0&&e.status!=="compliant"){t.push("Suggestions:");for(let s of e.suggestions)s&&t.push(` ${s}`);}return t.join(`
6
- `)}function k(e){if(e.status==="compliant")return {status:"ok",message:`${e.properlyDeclared.length} gates properly declared`};if(e.status==="warnings"){let t=[];return e.routeAttachedUnused.length>0&&t.push(`${e.routeAttachedUnused.length} route-attached`),e.orphanUnused.length>0&&t.push(`${e.orphanUnused.length} orphan`),{status:"warn",message:t.length>0?t.join(", ")+" gate(s)":`${e.declaredButUnused.length} unused gates`}}return {status:"error",message:`${e.usedButUndeclared.length} gates used but not declared`}}export{S as a,C as b,x as c,w as d,_ as e,k as f};
@@ -1,6 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a,e,d}from'./chunk-QO7YPQXC.js';import'./chunk-5TAVYPOV.js';import*as c from'fs';import*as p from'path';import {execSync}from'child_process';import n from'chalk';import*as w from'js-yaml';function R(s){return s.match(/(?:^|\s)((?:\/|\.\/|[a-zA-Z0-9_-]+\/)[^\s,;:'"]+\.[a-zA-Z]{1,10})\b/)?.[1]}async function $(s,l){try{let a$1=a(s),f=[];try{f=execSync("git diff --name-only HEAD",{cwd:s,encoding:"utf8",timeout:5e3}).trim().split(`
3
- `).filter(Boolean);}catch{}let i;try{i=execSync("git status --porcelain",{cwd:s,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let u=p.join(s,"portal.yaml"),g=!1;if(c.existsSync(u))try{let t=c.readFileSync(u,"utf8"),e=w.load(t);g=e?.routes!=null&&Object.keys(e.routes).length>0;}catch{}let r=e({toolsCalled:[],filesModified:f,symbolsTouched:[],loreRecorded:!1,hasPortalRoutes:g,taskAddsRoutes:!1,gitClean:i}),o=d(a$1,l,r),d$1=0;if(o.evaluations.length>0)try{let t=p.join(s,".paradigm","sentinel");if(c.existsSync(t)){let{SentinelStorage:e}=await import('./dist-VGFSP3XM.js'),m=new e(t);for(let b of o.evaluations)m.recordPracticeEvent({habitId:b.habit.id,habitCategory:b.habit.category,result:b.result,engineer:"agent",sessionId:`cli-${Date.now().toString(36)}`,symbolsTouched:[],filesModified:f,notes:b.reason}),d$1++;}}catch{}let h=p.join(s,".paradigm",".habits-blocking");try{if(l==="on-stop"&&o.blocksCompletion){let t=o.evaluations.filter(e=>e.result==="skipped"&&e.habit.severity==="block").map(e=>`${e.habit.name}: ${e.reason}`);c.writeFileSync(h,t.join(`
4
- `),"utf8");}else l==="on-stop"&&c.existsSync(h)&&c.unlinkSync(h);}catch{}return {trigger:l,evaluation:{total:o.summary.total,followed:o.summary.followed,skipped:o.summary.skipped,partial:o.summary.partial,blockingViolations:o.summary.blockingViolations,blocksCompletion:o.blocksCompletion},habits:o.evaluations.map(t=>({id:t.habit.id,name:t.habit.name,category:t.habit.category,severity:t.habit.severity,result:t.result,reason:t.reason,evidence:t.evidence})),recorded:d$1}}catch{return null}}async function P(s,l){let a=p.join(s,".paradigm","aspect-graph.db");if(!c.existsSync(a))return {driftedCount:0,healedCount:0,cleanCount:0,missingCount:0,details:[]};try{let{driftCheckCommand:f}=await import('./drift-ILZE5BFJ.js'),i="",u=console.log;console.log=g=>{i=g;};try{await f({json:!0,autoHeal:l});}finally{console.log=u;}return i?JSON.parse(i):null}catch{return null}}async function B(s){if(!c.existsSync(p.join(s,"portal.yaml")))return null;try{let{checkPortalCompliance:l}=await import('./portal-compliance-4MG5F2GI.js'),a=await l(s);return {status:a.status,declaredButUnusedCount:a.declaredButUnused.length,usedButUndeclaredCount:a.usedButUndeclared.length,properlyDeclaredCount:a.properlyDeclared.length,declaredButUnused:a.declaredButUnused,usedButUndeclared:a.usedButUndeclared,properlyDeclared:a.properlyDeclared}}catch{return null}}async function j(s){try{let{runPostflightLearning:l}=await import('./ambient-WTLYUAQM.js');return await l(s)}catch{return null}}async function A(s){let l=process.cwd(),a=s.trigger||"on-stop",f=s.autoHeal!==false,i=[],u=[],g=await $(l,a),r=await P(l,f),o=await B(l);if(g?.evaluation.blocksCompletion){let t=g.habits.filter(e=>e.result==="skipped"&&e.severity==="block");for(let e of t){let m=`Blocking habit not satisfied: ${e.name} \u2014 ${e.reason}`;i.push(m),u.push({message:m,source:"habits",file:R(e.reason),severity:"blocking"});}}if(r&&r.driftedCount>0){let t=`${r.driftedCount} aspect anchor(s) have drifted (content genuinely changed). Run paradigm_aspect_check to review.`;i.push(t);for(let e of r.details.filter(m=>m.status==="drifted"))u.push({message:`Aspect ~${e.aspectId} drifted at lines ${e.startLine}-${e.endLine}`,source:"drift",file:e.path,severity:"advisory"});u.filter(e=>e.source==="drift").length===0&&u.push({message:t,source:"drift",severity:"advisory"});}if(o&&o.usedButUndeclaredCount>0){let t=`${o.usedButUndeclaredCount} gate(s) used in code but not declared in portal.yaml: ${o.usedButUndeclared.join(", ")}`;i.push(t);for(let e of o.usedButUndeclared)u.push({message:`Gate ^${e} used in code but not declared in portal.yaml`,source:"portal",file:"portal.yaml",severity:"blocking"});}let d=null;s.learn&&(d=await j(l));let h={habits:g,drift:r,portal:o,violations:i,structuredViolations:u,postflight:s.learn?d:void 0};if(s.json)console.log(JSON.stringify(h));else {if(console.log(n.magenta(`
5
- Paradigm Compliance Check
6
- `)),g){let{evaluation:t}=g,e=t.blocksCompletion?n.red:n.green;console.log(n.white(" Habits:")),console.log(` ${e(`${t.followed} followed, ${t.skipped} skipped, ${t.partial} partial`)}`),t.blockingViolations>0&&console.log(n.red(` ${t.blockingViolations} blocking violation(s)`)),console.log();}if(r&&(console.log(n.white(" Drift:")),r.healedCount>0&&console.log(n.green(` Auto-healed: ${r.healedCount} shifted anchor(s)`)),r.cleanCount>0&&console.log(n.green(` Clean: ${r.cleanCount} anchor(s)`)),r.driftedCount>0&&console.log(n.red(` Drifted: ${r.driftedCount} anchor(s)`)),r.missingCount>0&&console.log(n.yellow(` Missing: ${r.missingCount} anchor file(s)`)),console.log()),o){console.log(n.white(" Portal:"));let t=o.status==="compliant"?n.green:o.status==="warnings"?n.yellow:n.red;console.log(` Status: ${t(o.status)}`),o.usedButUndeclaredCount>0&&console.log(n.red(` ${o.usedButUndeclaredCount} undeclared gate(s)`)),console.log();}if(d){if(console.log(n.white(" Postflight Learning:")),d.journalsWritten>0){console.log(n.green(` Journals written: ${d.journalsWritten}`));for(let[t,e]of Object.entries(d.journalsByAgent))e>0&&console.log(n.gray(` ${t}: ${e} entries`));}else console.log(n.gray(" No verdicts to learn from"));d.promoted>0&&console.log(n.green(` Promoted to notebooks: ${d.promoted}`)),console.log();}if(i.length>0){console.log(n.red(` ${i.length} violation(s):`));for(let t of i)console.log(n.red(` - ${t}`));}else console.log(n.green(" All checks passed."));console.log();}i.length>0&&(process.exitCode=1);}export{A as complianceCheckCommand};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as x from'fs';import*as C from'js-yaml';import {z as z$1}from'zod';import*as S from'path';import {glob}from'glob';var O=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(),L=O.extend({id:z$1.string()}),fe=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()}),le=z$1.union([fe,z$1.string().transform(t=>({description:t}))]),ue=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),de=z$1.union([ue,z$1.string()]),me=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),B=z$1.union([me,z$1.string()]),ge=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(B)}),he=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(B).optional()}),ye=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()}),$e=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),we=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()}),be=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),Se=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(L),z$1.record(O)]).optional(),components:z$1.union([z$1.array(L),z$1.record(O)]).optional(),gates:z$1.record(ye).optional(),states:z$1.record($e).optional(),signals:z$1.record(le).optional(),aspects:z$1.record(we).optional(),relationships:z$1.array(de).optional(),flows:z$1.union([z$1.array(ge),z$1.record(he)]).optional(),references:z$1.array(be).optional()});function ve(t){let e=Pe(t);return {data:e.data,errors:e.errors}}function Pe(t){let e=[],o=[],n;try{n=x.readFileSync(t,"utf8");}catch(l){let p=`Cannot read file: ${l.message}`;return e.push(p),o.push({message:p,type:"file"}),{data:null,errors:e,detailedErrors:o,rawContent:void 0,isYamlValid:false}}let r=n.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),a=null;try{a=C.load(r);}catch(l){let p=l,f=p.mark?.line?p.mark.line+1:void 0,u=`YAML syntax error: ${p.reason||l.message}`;return e.push(`${u}${f?` (line ${f})`:""}`),o.push({message:u,line:f,type:"yaml"}),{data:null,errors:e,detailedErrors:o,rawContent:n,isYamlValid:false}}if(a==null)return {data:{},errors:[],detailedErrors:[],rawContent:n,isYamlValid:true};if(typeof a=="object"&&a!==null){let l=a,p={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let f of Object.keys(l)){let u=f[0],g=p[u];if(!g||f.length<2)continue;let h=f.slice(1),w=l[f];if(typeof w!="object"||w===null)continue;let v=l[g]||{};g in l||(l[g]=v),h in v||(v[h]=w),delete l[f];}}let i=Se.safeParse(a);if(!i.success){for(let l of i.error.issues){let p=l.path.join("."),f=l.message;e.push(`Schema error at ${p||"/"}: ${f}`),o.push({message:f,path:p||"/",type:"schema"});}return {data:a,errors:e,detailedErrors:o,rawContent:n,isYamlValid:true}}return {data:i.data,errors:[],detailedErrors:[],rawContent:n,isYamlValid:true}}function k(t){return t?Array.isArray(t)?t.map(e=>[e.id,e]):Object.entries(t):[]}async function je(t){let e=S.resolve(t);return (await glob("**/.purpose",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((n,r)=>{let a=n.split(S.sep).length,i=r.split(S.sep).length;return a-i})}async function V(t){let e=await je(t),o=[];for(let n of e){let{data:r,errors:a}=ve(n);r&&(o.push({filePath:n,data:r}),a.length>0&&console.warn(`Warnings parsing ${n}:`,a));}return o}function Y(t){let e=new Map;for(let{filePath:o,data:n}of t){let r=k(n.features);for(let[a,i]of r)e.set(a,{item:i,filePath:o});}return e}function W(t){let e=new Map;for(let{filePath:o,data:n}of t){let r=k(n.components);for(let[a,i]of r)e.set(a,{item:i,filePath:o});}return e}function _(t){let e=new Map;for(let{filePath:o,data:n}of t)if(n.gates)for(let[r,a]of Object.entries(n.gates))e.set(r,{item:a,filePath:o});return e}function N(t){let e=new Map;for(let{filePath:o,data:n}of t)if(n.states)for(let[r,a]of Object.entries(n.states))e.set(r,{item:a,filePath:o});return e}function K(t){let e=new Map;for(let{filePath:o,data:n}of t)if(n.flows)if(Array.isArray(n.flows))for(let r of n.flows)e.set(r.name,{item:{id:r.name,description:r.description,steps:r.steps},filePath:o});else for(let[r,a]of Object.entries(n.flows))e.set(r,{item:{id:r,description:a.description,gates:a.gates,signals:a.signals,components:a.components,steps:a.steps},filePath:o});return e}function q(t){let e=new Map;for(let{filePath:o,data:n}of t)if(n.signals)for(let[r,a]of Object.entries(n.signals))e.set(r,{item:a,filePath:o});return e}function Z(t){let e=new Map;for(let{filePath:o,data:n}of t)if(n.aspects)for(let[r,a]of Object.entries(n.aspects))e.set(r,{item:a,filePath:o});return e}function U(t){let e=[],o=new Set;for(let{filePath:n,data:r}of t){let a=k(r.features);for(let[l,p]of a)M(`#${l}`,p,n,e,o);let i=k(r.components);for(let[l,p]of i)M(`#${l}`,p,n,e,o);}return e}function M(t,e,o,n,r){if(e.flows)for(let a of e.flows){let i=a.startsWith("$")?a:`$${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"flow",sourceSymbol:t,filePath:o}));}if(e.gates)for(let a of e.gates){let i=a.startsWith("^")?a:`^${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"gate",sourceSymbol:t,filePath:o}));}if(e.signals)for(let a of e.signals){let i=a.startsWith("!")?a:`!${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"signal",sourceSymbol:t,filePath:o}));}if(e.states)for(let a of e.states){let i=a.startsWith("#")?a:a.startsWith("%")?`#${a.slice(1)}`:`#${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"component",sourceSymbol:t,filePath:o}));}if(e.components)for(let a of e.components){let i=a.startsWith("#")?a:`#${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"component",sourceSymbol:t,filePath:o}));}if(e.aspects)for(let a of e.aspects){let i=a.startsWith("~")?a:`~${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"aspect",sourceSymbol:t,filePath:o}));}if(e.description){let a=Ce(e.description);for(let{symbol:i,type:l}of a)r.has(i)||(r.add(i),n.push({symbol:i,type:l,sourceSymbol:t,filePath:o}));}}var ke=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Ce(t){let e=[],o=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,n;for(;(n=o.exec(t))!==null;){let r=n[1],a=n[2],i,l;switch(r){case "#":l="component",i=`#${a}`;break;case "$":l="flow",i=`$${a}`;break;case "^":l="gate",i=`^${a}`;break;case "!":l="signal",i=`!${a}`;break;case "~":l="aspect",i=`~${a}`;break;case "%":l="component",i=`#${a}`;break;default:continue}ke.has(i)||e.push({symbol:i,type:l});}return e}var Ie={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function I(t){let e=S.resolve(t),o=S.dirname(e);if(!x.existsSync(e))throw new Error(`Gate config not found: ${e}`);let n=x.readFileSync(e,"utf8"),r=C.load(n);if(!r.version)throw new Error('Gate config missing required "version" field');let a=[],i=r,l=r.gates||i.portals;if(l)for(let[f,u]of Object.entries(l))a.push(F(f,u));if(r.include)for(let f of r.include){let u=S.join(o,f),g=await glob(u.replace(/\\/g,"/"));for(let h of g){let w=await Ae(h);a.push(...w);}}let p=[];if(r.flows)for(let[f,u]of Object.entries(r.flows))p.push(Oe(f,u));return {version:r.version,gates:a,flows:p,settings:{dev:{...Ie,...r.settings?.dev}}}}async function Ae(t){let e=x.readFileSync(t,"utf8"),o=C.load(e);if(o.id)return [F(o.id,o)];if(o.gates){let n=[];for(let[r,a]of Object.entries(o.gates))n.push(F(r,a));return n}return []}function F(t,e){let o=[];if(e.locks)for(let r of e.locks)o.push(De(r));let n=[];if(e.prizes)for(let r of e.prizes)n.push(ze(r));return {id:t,description:e.description,locks:o,prizes:n,position:e.position}}function De(t){let e=t,o=[];if(e.keys){for(let n of e.keys)if(typeof n=="string")o.push({expression:n});else if(n.expression){let r=n;o.push({expression:r.expression,description:r.description});}}return {id:e.id,description:e.description,keys:o,mode:e.mode||"all"}}function ze(t){let e=t;return {id:e.id,oneTime:e.oneTime??false,metadata:e.metadata}}function Oe(t,e){return {id:t,description:e.description,gates:e.gates||[],forkable:e.forkable}}async function H(t){let e=S.resolve(t);return await glob("**/portal.yaml",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}var Ee={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Fe={"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"},Te=["#","$","^","!","~"];function Re(t){return Te.includes(t)}var Le=z$1.object({x:z$1.number(),y:z$1.number()}),Me=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),J=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),ee=z$1.object({id:z$1.string(),symbol:z$1.string(),type:z$1.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z$1.string().optional(),position:Le,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),te=z$1.object({from:z$1.string(),to:z$1.string(),label:z$1.string().optional(),type:z$1.string().optional()}),Ge=z$1.object({id:z$1.string(),name:z$1.string(),nodes:z$1.array(z$1.string()),color:z$1.string().optional()}),oe=z$1.object({viewport:Me,groups:z$1.array(Ge).optional()}),Be=z$1.object({nodes:z$1.array(ee),connections:z$1.array(te),layout:oe}),Ve=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:Be}),Ye=z$1.object({version:z$1.string(),metadata:z$1.object({name:z$1.string(),created:z$1.string(),modified:z$1.string()}),sources:z$1.object({purpose:z$1.array(J).optional(),portal:z$1.array(J).optional()}),nodes:z$1.array(ee),connections:z$1.array(te),layout:oe,snapshots:z$1.array(Ve).optional()});function nt(t){let e=[],o;try{o=x.readFileSync(t,"utf8");}catch(n){return e.push(`Cannot read file: ${n.message}`),{data:null,errors:e,rawContent:void 0}}return We(o)}function We(t){let e=[],o=null;try{o=C.load(t);}catch(r){let a=r,i=a.mark?.line?a.mark.line+1:void 0;return e.push(`YAML syntax error: ${a.reason||r.message}${i?` (line ${i})`:""}`),{data:null,errors:e,rawContent:t}}if(o==null)return {data:se(),errors:[],rawContent:t};let n=Ye.safeParse(o);if(!n.success){for(let r of n.error.issues){let a=r.path.join(".");e.push(`Schema error at ${a||"/"}: ${r.message}`);}return {data:o,errors:e,rawContent:t}}return {data:n.data,errors:[],rawContent:t}}function se(t="Untitled"){let e=new Date().toISOString();return {version:"1.0.0",metadata:{name:t,created:e,modified:e},sources:{purpose:[{path:"./"}],portal:[{path:"./portal.yaml"}]},nodes:[],connections:[],layout:{viewport:{x:0,y:0,zoom:1}}}}function _e(t){return t.metadata.modified=new Date().toISOString(),C.dump(t,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function rt(t="My Project"){return _e(se(t))}function at(t,e){return {...t,nodes:[...t.nodes,e],metadata:{...t.metadata,modified:new Date().toISOString()}}}function it(t,e,o){return {...t,nodes:t.nodes.map(n=>n.id===e?{...n,position:o,modified:new Date().toISOString()}:n),metadata:{...t.metadata,modified:new Date().toISOString()}}}function ct(t,e){return t.connections.some(n=>n.from===e.from&&n.to===e.to)?t:{...t,connections:[...t.connections,e],metadata:{...t.metadata,modified:new Date().toISOString()}}}function pt(t,e,o){let n={id:`snap-${Date.now()}`,name:e,timestamp:new Date().toISOString(),description:o,state:{nodes:[...t.nodes],connections:[...t.connections],layout:{...t.layout}}};return {...t,snapshots:[...t.snapshots||[],n],metadata:{...t.metadata,modified:new Date().toISOString()}}}async function Ne(t,e){let o=[],n=[],r=[],a=[];if(t.sources.purpose)for(let p of t.sources.purpose){let f=S.resolve(e,p.path);try{let u=await V(f);r.push(...u.map(d=>d.filePath));let g=Y(u);for(let[d,{item:m,filePath:y}]of g){let P=["feature",...m.tags||[]];o.push($({id:`purpose-feature-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:y,data:m,description:m.description,tags:P,componentType:m.type,parentSymbol:m.parent,anchors:m.anchors?.map(pe=>T(pe))}));}let h=W(u);for(let[d,{item:m,filePath:y}]of h)o.push($({id:`purpose-component-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:y,data:m,description:m.description,tags:m.tags,componentType:m.type,parentSymbol:m.parent,anchors:m.anchors?.map(P=>T(P))}));let w=_(u);for(let[d,{item:m,filePath:y}]of w)o.push($({id:`purpose-gate-${d}`,symbol:`^${d}`,type:"gate",source:"purpose",filePath:y,data:m,description:m.description}));let v=N(u);for(let[d,{item:m,filePath:y}]of v)o.push($({id:`purpose-state-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:y,data:m,description:m.description,tags:["state"]}));let re=K(u);for(let[d,{item:m,filePath:y}]of re)o.push($({id:`purpose-flow-${d}`,symbol:`$${d}`,type:"flow",source:"purpose",filePath:y,data:m,description:m.description}));let ae=q(u);for(let[d,{item:m,filePath:y}]of ae)o.push($({id:`purpose-signal-${d}`,symbol:`!${d}`,type:"signal",source:"purpose",filePath:y,data:m,description:m.description}));let ie=Z(u);for(let[d,{item:m,filePath:y}]of ie)o.push($({id:`purpose-aspect-${d}`,symbol:`~${d}`,type:"aspect",source:"purpose",filePath:y,data:m,description:m.description,anchors:m.anchors?.map(P=>T(P)),appliesTo:m["applies-to"],tags:m.tags,enforcement:m.enforcement}));let ce=U(u),R=new Set(o.map(d=>d.symbol));for(let d of ce)R.has(d.symbol)||(R.add(d.symbol),o.push($({id:`purpose-ref-${d.type}-${d.symbol.slice(1)}`,symbol:d.symbol,type:d.type,source:"purpose",filePath:d.filePath,data:{referencedFrom:d.sourceSymbol},description:`Referenced from ${d.sourceSymbol}`})));}catch(u){n.push({source:"purpose",filePath:f,message:u.message});}}if(t.sources.portal)for(let p of t.sources.portal){let f=S.resolve(e,p.path);try{let u;if(f.endsWith(".yaml")||f.endsWith(".yml"))u=await I(f),a.push(f);else {let g=await H(f);if(a.push(...g),g.length>0){u=await I(g[0]);for(let h=1;h<g.length;h++){let w=await I(g[h]);u.gates.push(...w.gates),u.flows.push(...w.flows);}}else continue}for(let g of u.gates){o.push(Ke(g,f));for(let h of g.prizes)o.push($({id:`gate-signal-${g.id}-${h.id}`,symbol:`!${h.id}`,type:"signal",source:"portal",filePath:f,data:h,description:`Signal from gate ${g.id}`}));}for(let g of u.flows)o.push(qe(g,f));}catch(u){n.push({source:"portal",filePath:f,message:u.message});}}for(let p of t.nodes){let f=p.tags?.includes("idea");if(!p.content&&!f){let u=o.find(g=>g.symbol===p.symbol);if(u){u.position=p.position,u.tags=p.tags;continue}}o.push($({id:p.id,symbol:p.symbol,type:p.type,source:"premise",filePath:".premise",data:p,description:p.content,position:p.position,tags:p.tags,created:p.created,modified:p.modified}));}Ue(o);let i=new Map;for(let p of o){let f=i.get(p.symbol)||[];f.includes(p.filePath)||f.push(p.filePath),i.set(p.symbol,f);}let l=[];for(let[p,f]of i)f.length>1&&l.push({symbol:p,files:f});return {symbols:o,purposeFiles:r,portalFiles:a,errors:n,timestamp:Date.now(),...l.length>0?{duplicateSymbols:l}:{}}}function $(t){return {...t,data:t.data??null,references:t.references??[],referencedBy:t.referencedBy??[]}}function Ke(t,e){return $({id:`gate-${t.id}`,symbol:`^${t.id}`,type:"gate",source:"portal",filePath:e,data:t,description:t.description,position:t.position})}function qe(t,e){return $({id:`gate-flow-${t.id}`,symbol:`$${t.id}`,type:"flow",source:"portal",filePath:e,data:t,description:t.description})}function T(t){let e=t.lastIndexOf(":");if(e===-1||e===t.length-1)return {path:t,lines:0,raw:t};let o=t.slice(e+1),n=t.slice(0,e);if(!/^[\d,\- ]+$/.test(o))return {path:t,lines:0,raw:t};if(o.includes("-")){let[r,a]=o.split("-").map(Number);return {path:n,lines:[r,a],raw:t}}else if(o.includes(",")){let r=o.split(",").map(Number);return {path:n,lines:r,raw:t}}else return {path:n,lines:Number(o),raw:t}}var Ze=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Ue(t){let e=new Map(t.map(o=>[o.symbol,o]));for(let o of t){let n=JSON.stringify(o.data),r=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,a=(n.match(r)||[]).filter(i=>!Ze.has(i));for(let i of a)if(i!==o.symbol&&e.has(i)){o.references.includes(i)||o.references.push(i);let l=e.get(i);l&&!l.referencedBy.includes(o.symbol)&&l.referencedBy.push(o.symbol);}}}async function ut(t){let e={metadata:{name:S.basename(t),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return Ne(e,t)}function Xe(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function dt(t){let e=Xe();e.timestamp=t.timestamp;for(let o of t.symbols)e.entries.set(o.id,o),e.byType.has(o.type)||e.byType.set(o.type,[]),e.byType.get(o.type).push(o),e.bySource.has(o.source)||e.bySource.set(o.source,[]),e.bySource.get(o.source).push(o);return e}function A(t,e){for(let o of t.entries.values())if(o.symbol===e)return o}function mt(t,e){return t.entries.get(e)}function z(t,e){return t.byType.get(e)||[]}function gt(t,e){return t.bySource.get(e)||[]}function He(t,e){let o=e.toLowerCase(),n=[];for(let r of t.entries.values()){if(r.symbol.toLowerCase().includes(o)){n.push(r);continue}if(r.description?.toLowerCase().includes(o)){n.push(r);continue}if(r.tags?.some(a=>a.toLowerCase().includes(o))){n.push(r);continue}if(r.componentType?.toLowerCase().includes(o)){n.push(r);continue}}return n}function ht(t,e){return z(t,"component").filter(n=>n.componentType===e)}function yt(t){let e=new Set,o=z(t,"component");for(let n of o)n.componentType&&e.add(n.componentType);return Array.from(e).sort()}function $t(t,e){return z(t,"component").filter(n=>n.parentSymbol===e)}function wt(t,e){let o=A(t,e);return o?o.referencedBy.map(n=>A(t,n)).filter(n=>n!==void 0):[]}function bt(t,e){let o=A(t,e);return o?o.references.map(n=>A(t,n)).filter(n=>n!==void 0):[]}function St(t,e){let o=[];for(let n of t.entries.values())n.tags?.includes(e)&&o.push(n);return o}function vt(t){let e=new Set;for(let o of t.entries.values())for(let n of o.tags||[])e.add(n);return Array.from(e).sort()}function Pt(t){let e={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[o,n]of t.byType)o in e&&(e[o]=n.length);return e}function xt(t){return Array.from(t.entries.values())}function ne(t){if(t.length<2)return null;let e=t[0],o=t.slice(1);return Re(e)?{type:Fe[e],name:o}:null}function jt(t,e){return `${Ee[t]}${e}`}function kt(t){return ne(t)!==null}function Ct(t,e,o=10){let n=e.toLowerCase(),r=ne(e);return r?z(t,r.type).filter(i=>i.symbol.toLowerCase().includes(n)).slice(0,o):He(t,e).slice(0,o)}export{Fe as PREFIX_TO_TYPE,Ee as SYMBOL_PREFIXES,ct as addConnection,at as addPremiseNode,ut as aggregateFromDirectory,Ne as aggregateFromPremise,dt as buildSymbolIndex,se as createEmptyPremiseFile,pt as createSnapshot,Xe as createSymbolIndex,jt as createSymbolString,yt as getAllComponentTypes,xt as getAllSymbols,vt as getAllTags,Ct as getAutocompleteSuggestions,$t as getChildComponents,ht as getComponentsByType,rt as getDefaultPremiseContent,bt as getReferencesFrom,wt as getReferencesTo,A as getSymbol,mt as getSymbolById,Pt as getSymbolCounts,gt as getSymbolsBySource,St as getSymbolsByTag,z as getSymbolsByType,kt as isValidSymbol,We as parsePremiseContent,nt as parsePremiseFile,ne as parseSymbol,He as searchSymbols,_e as serializePremiseFile,it as updateNodePosition};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{e as findGateFiles,g as formatValidationResult,d as getDefaultGateConfig,a as parseGateConfig,b as parseGateFile,c as serializeGateConfig,f as validateGateConfig}from'./chunk-QT2LKB3P.js';import'./chunk-5TAVYPOV.js';
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{a as doctorCommand}from'./chunk-G7XFK2GI.js';import'./chunk-DOCDDDTD.js';import'./chunk-JQKKVAAN.js';import'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{a as initCommand}from'./chunk-CHVQNRRT.js';import'./chunk-LBQBWIEX.js';import'./chunk-4TXOVRWD.js';import'./chunk-VCKKJDLP.js';import'./chunk-WR6D3SC6.js';import'./chunk-UIKLE3WD.js';import'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-DOCDDDTD.js';import'./chunk-JQKKVAAN.js';import'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';
@@ -1,8 +0,0 @@
1
- #!/usr/bin/env node
2
- import {d,e}from'./chunk-SHD27BQX.js';import'./chunk-5TAVYPOV.js';import n from'chalk';async function c(l){let s=process.cwd(),e$1=await d(s);if(l.json)console.log(JSON.stringify({status:e$1.status,declaredButUnusedCount:e$1.declaredButUnused.length,usedButUndeclaredCount:e$1.usedButUndeclared.length,properlyDeclaredCount:e$1.properlyDeclared.length,declaredButUnused:e$1.declaredButUnused,usedButUndeclared:e$1.usedButUndeclared,properlyDeclared:e$1.properlyDeclared}));else {let o=e(e$1);e$1.status==="compliant"?console.log(n.green(`
3
- ${o}
4
- `)):e$1.status==="warnings"?console.log(n.yellow(`
5
- ${o}
6
- `)):console.log(n.red(`
7
- ${o}
8
- `));}}export{c as portalCheckCommand};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{d as checkPortalCompliance,b as extractDeclaredGates,c as findGateReferences,e as formatComplianceReport,f as getComplianceSummary,a as loadPortalConfig}from'./chunk-SHD27BQX.js';import'./chunk-5TAVYPOV.js';
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{d as detectProjectRole,a as workspaceInitCommand,c as workspaceReindexCommand,b as workspaceStatusCommand}from'./chunk-SUU6M4JH.js';import'./chunk-LBQBWIEX.js';import'./chunk-4TXOVRWD.js';import'./chunk-VCKKJDLP.js';import'./chunk-WR6D3SC6.js';import'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';