@a-company/paradigm 7.0.0 → 7.1.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 (67) hide show
  1. package/dist/{accept-orchestration-YO2V2WYA.js → accept-orchestration-WMGFGYDK.js} +1 -1
  2. package/dist/{agent-loader-VGBPL3TH.js → agent-loader-Z753DQWH.js} +1 -1
  3. package/dist/{ambient-OX7YJ4PJ.js → ambient-HAXPDIWK.js} +1 -1
  4. package/dist/ambient-OW5M5LVN.js +2 -0
  5. package/dist/ambient-QB7V4TBR.js +6 -0
  6. package/dist/calibrate-PHVP7RPH.js +4 -0
  7. package/dist/{captain-YUP3KVCA.js → captain-3COP6YTD.js} +1 -1
  8. package/dist/chunk-4CGPLLWQ.js +30 -0
  9. package/dist/{chunk-3MZ4J2LF.js → chunk-CHSU6LTR.js} +1 -1
  10. package/dist/chunk-ECO3LHCE.js +2 -0
  11. package/dist/chunk-EG22HDXI.js +33 -0
  12. package/dist/{chunk-GD4F2HC6.js → chunk-H55W26AR.js} +1 -1
  13. package/dist/{chunk-ROU3F2HZ.js → chunk-HSY75GRR.js} +3 -3
  14. package/dist/chunk-KAUGQMXU.js +4 -0
  15. package/dist/{chunk-QBIQ2FYB.js → chunk-KP5VOYAH.js} +1 -1
  16. package/dist/{chunk-K54L6CFR.js → chunk-OIYJUU6T.js} +4 -4
  17. package/dist/{chunk-47YPID6H.js → chunk-RDWWSQGH.js} +21 -21
  18. package/dist/chunk-RVXQNS6K.js +30 -0
  19. package/dist/{chunk-WROJSWAO.js → chunk-VPNJL4LS.js} +1 -1
  20. package/dist/{chunk-JCGCPAHF.js → chunk-W4BW7GXA.js} +1 -1
  21. package/dist/chunk-XPPFILCM.js +2 -0
  22. package/dist/{chunk-V6MIKLMY.js → chunk-YCDOA5IQ.js} +1 -1
  23. package/dist/chunk-YQK3XU63.js +504 -0
  24. package/dist/{compliance-MLG4W6S4.js → compliance-4P3EE5OA.js} +1 -1
  25. package/dist/{diff-MC6AXLKX.js → diff-VBVIUNL5.js} +1 -1
  26. package/dist/{docs-3YFNNZRV.js → docs-NTP6UENF.js} +1 -1
  27. package/dist/index.js +5 -5
  28. package/dist/journal-loader-CNNA4EAU.js +2 -0
  29. package/dist/lore-loader-HAZ5FRLP.js +2 -0
  30. package/dist/mcp.js +1 -1
  31. package/dist/nomination-engine-ORHH4L2W.js +2 -0
  32. package/dist/{nomination-engine-AQHU2KBU.js → nomination-engine-YRHZZZUN.js} +1 -1
  33. package/dist/notebook-loader-TZVIMNDJ.js +2 -0
  34. package/dist/{orchestrate-GMYEBA5T.js → orchestrate-MLUGQOEJ.js} +1 -1
  35. package/dist/orchestration-O2OVPTIZ.js +2 -0
  36. package/dist/{platform-server-WIBVYHIV.js → platform-server-Y6TLEXR2.js} +1 -1
  37. package/dist/{reindex-XTRF23F7.js → reindex-ZLDQBFUR.js} +1 -1
  38. package/dist/{serve-SMGWGJLM.js → serve-XZ6GBUS3.js} +1 -1
  39. package/dist/{session-work-log-QXPAXY5K.js → session-work-log-FF7CKMWP.js} +1 -1
  40. package/dist/{shift-JBCEDCGA.js → shift-PM4GI736.js} +1 -1
  41. package/dist/{symphony-G6IENE4K.js → symphony-CFAYJGLF.js} +1 -1
  42. package/dist/{symphony-7INZR43F.js → symphony-L56O5ZG3.js} +3 -3
  43. package/dist/{symphony-relay-2RHG25Z4.js → symphony-relay-Y2UR3YNR.js} +1 -1
  44. package/dist/{task-loader-IGQQ6ZFL.js → task-loader-H7HQAYGL.js} +1 -1
  45. package/dist/task-loader-YZME4RKE.js +2 -0
  46. package/dist/{task-settlement-NW4XMJGJ.js → task-settlement-HINBVZBE.js} +2 -2
  47. package/dist/task-settlement-XC6E6JNT.js +3 -0
  48. package/dist/{team-J2YXPEGX.js → team-25LK6CWM.js} +1 -1
  49. package/dist/tools-GAU5WOEI.js +2 -0
  50. package/dist/university-ui/assets/{index-B8hm_MdR.js → index-AbTjHBCf.js} +2 -2
  51. package/dist/university-ui/assets/{index-B8hm_MdR.js.map → index-AbTjHBCf.js.map} +1 -1
  52. package/dist/university-ui/index.html +1 -1
  53. package/dist/work-log-loader-CRVTOMVB.js +2 -0
  54. package/package.json +1 -1
  55. package/dist/ambient-7HBJHJL2.js +0 -2
  56. package/dist/ambient-SST5CLEC.js +0 -35
  57. package/dist/chunk-6AKNXD22.js +0 -32
  58. package/dist/chunk-FRQRREJ6.js +0 -29
  59. package/dist/chunk-QEQCPVF5.js +0 -4
  60. package/dist/chunk-QGZRM6ZB.js +0 -2
  61. package/dist/chunk-S4J337EQ.js +0 -504
  62. package/dist/journal-loader-GLH7XFTK.js +0 -2
  63. package/dist/lore-loader-D2ISOASW.js +0 -2
  64. package/dist/notebook-loader-6DYFMNJ2.js +0 -2
  65. package/dist/orchestration-G5MAY6IA.js +0 -2
  66. package/dist/tools-HNJ7D5IO.js +0 -2
  67. /package/dist/{chunk-CVPKQ3JH.js → chunk-HE2NA5QF.js} +0 -0
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {n as n$4,j as j$1,P,O as O$1,K,Q as Q$1,L,I,J as J$1,D as D$1,H as H$2,m as m$3,l as l$3,E,v as v$2,N,q as q$2,C as C$1,S as S$1,o as o$4,z as z$3,t as t$1,B as B$1,s as s$2}from'./chunk-ZUAUFZRJ.js';import {a as a$5,b as b$4}from'./chunk-S4J337EQ.js';import {n as n$1,h,l as l$1,q as q$1,C,s,A as A$1,u,m as m$1,r,D,t,B,v as v$1,k as k$1,e as e$1,g as g$1,f,c as c$1,o as o$3,p as p$1,x as x$2,y as y$3,w as w$1,z as z$5}from'./chunk-K54L6CFR.js';import {a as a$3,n as n$3,o as o$1,c as c$6,d as d$9,l as l$5,k as k$3,e as e$a,i as i$4,f as f$5,g as g$4,h as h$5,m as m$4,j as j$2,b as b$d}from'./chunk-WROJSWAO.js';import {Q,T,O,a as a$2,H as H$1,R,S,c as c$4,l as l$2,k as k$2,i as i$1,m as m$2,b as b$8,h as h$3,g as g$3,f as f$2,e as e$5,d as d$5,A as A$3,r as r$2,z as z$4,t as t$2,v as v$3,x as x$1,w,B as B$2,y as y$1,u as u$1,s as s$3,E as E$1,C as C$2,o as o$5,q as q$3}from'./chunk-QBIQ2FYB.js';import {a as a$6,b as b$5}from'./chunk-B5KLSBOZ.js';import {a as a$1,b as b$2}from'./chunk-4UJ4NIEQ.js';import {a as a$4,b as b$3}from'./chunk-ROU3F2HZ.js';import {e,v,n,c as c$2,d}from'./chunk-FRQRREJ6.js';import {i,f as f$3,e as e$7,c as c$5,b as b$a}from'./chunk-QEQCPVF5.js';import {h as h$1,e as e$2,a as a$8,d as d$1}from'./chunk-Q527BPUF.js';import {a as a$7,b as b$b,d as d$7,e as e$8}from'./chunk-RGSFU2YW.js';import {l,p,k,n as n$2,o,m,q,r as r$1,s as s$1,b as b$c,e as e$9,d as d$8,t as t$3,c as c$7,h as h$6}from'./chunk-TMDPDIWA.js';import {o as o$2,A as A$2,y,x,f as f$4,r as r$3}from'./chunk-KLBH26PA.js';import {i as i$3}from'./chunk-XROULIQN.js';import {z as z$2,h as h$4,b as b$9,d as d$6,e as e$6,i as i$2,y as y$2,l as l$4}from'./chunk-KAFQA7HV.js';import {j}from'./chunk-ACJWUOMA.js';import {h as h$2,d as d$4,g as g$2,f as f$1,c as c$3,e as e$4}from'./chunk-3MZ4J2LF.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {d as d$3,b as b$7,a as a$a}from'./chunk-JNSJVCTU.js';import {g,e as e$3,b as b$6,d as d$2,a as a$9}from'./chunk-QGZRM6ZB.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as A from'fs';import*as $ from'path';import*as qe from'js-yaml';import*as Ni from'os';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import*as ct from'crypto';import {execSync}from'child_process';import {z as z$1}from'zod';import*as Qe from'fs/promises';var dt,Mn,Gn=b(()=>{dt={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"]},Mn=new Set(["tool-called","context-checked"]);});var Yi={};c(Yi,{getAllStates:()=>Un,getConfig:()=>Le,getState:()=>Ut,incrementFailure:()=>Vi,invalidateGraduationCache:()=>Uc,isGraduated:()=>Gc,loadGraduation:()=>Oe,markNeverGraduate:()=>Jc,saveGraduation:()=>Jt,setTier:()=>Bi});function zi(t){return $.join(t,".paradigm","graduation.yaml")}function Oe(t){let e=$.resolve(t);if(pt&&Lt===e&&Date.now()-Mt<Mc)return pt;let s=zi(e),n;if(A.existsSync(s))try{let r=A.readFileSync(s,"utf8");n=qe.load(r);}catch{n={version:"1.0",config:{},states:{}};}else n={version:"1.0",config:{},states:{}};return n.version||(n.version="1.0"),n.config||(n.config={}),n.states||(n.states={}),pt=n,Lt=e,Mt=Date.now(),n}function Jt(t,e){let s=$.resolve(t),n=zi(s),r=$.dirname(n);A.existsSync(r)||A.mkdirSync(r,{recursive:true});let i=qe.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});A.writeFileSync(n,i,"utf8"),pt=e,Lt=s,Mt=Date.now();}function Le(t){let e=Oe(t);return {...dt,...e.config,thresholds:{...dt.thresholds,...e.config?.thresholds},demotion:{...dt.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??dt.neverGraduate}}function Jn(t){return {habitId:t,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Ut(t,e){let n=Oe(t).states[e];return n?{...Jn(e),...n,habitId:e}:Jn(e)}function Un(t){let e=Oe(t),s={};for(let[n,r]of Object.entries(e.states))s[n]={...Jn(n),...r,habitId:n};return s}function Gc(t,e){return Ut(t,e).tier==="hook"}function Bi(t,e,s,n){let r=Oe(t),i=r.states[e]||{};r.states[e]={...i,tier:s,previousTier:i.tier||"habit",...s==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...s==="habit"&&i.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...n},Jt(t,r);}function Jc(t,e){let s=Oe(t);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",Jt(t,s);}function Vi(t,e){let s=Oe(t);s.states[e]||(s.states[e]={});let n=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=n,Jt(t,s),n}function Uc(){pt=null,Lt=null,Mt=0;}var pt,Lt,Mt,Mc,Wt=b(()=>{Gn();pt=null,Lt=null,Mt=0,Mc=3e4;});function _i(){return [{name:"paradigm_history_context",description:"Get implementation history for symbols before modifying. Shows recent changes, stability, and who has worked on these areas. Returns recent commits, authors, and change frequency. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get history for (e.g., ["@checkout", "#payment-form"])'}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_history_record",description:"Record an implementation event (feature, fix, refactor). Call this after making changes to track what was done. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["implement","refactor","rollback"],description:"Type of change"},symbols:{type:"array",items:{type:"string"},description:"Symbols affected by this change"},intent:{type:"string",enum:["feature","fix","refactor","experimental","confirmed"],description:"Intent of the change"},description:{type:"string",description:"What was done"},commit:{type:"string",description:"Git commit hash (optional)"},files:{type:"array",items:{type:"string"},description:"Files affected (optional)"},reason:{type:"string",description:"Reason for rollback (if type is rollback)"}},required:["type","symbols","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_validate",description:"Record a validation result (tests passed/failed). Call this after running tests. ~100 tokens.",inputSchema:{type:"object",properties:{implementation_id:{type:"string",description:"ID of the implementation being validated (from paradigm_history_record)"},result:{type:"string",enum:["pass","fail","partial"],description:"Validation result"},tests:{type:"object",properties:{passed:{type:"number"},failed:{type:"number"},skipped:{type:"number"}},description:"Test counts"}},required:["result"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_fragility",description:"Check fragility of symbols before modifying. Returns stability scores and warnings for fragile areas. Returns numeric stability scores (0-100) and actionable warnings. ~150 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols to check fragility for"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Si(t,e,s){switch(t){case "paradigm_history_context":{let{symbols:n}=e,r=await k$1(s),i=c$1(r,n),o={symbols:n,history:i.map(a=>({symbol:a.symbol,summary:a.summary?{total_changes:a.summary.total_changes,last_modified:a.summary.last_modified,stability_score:a.summary.stability_score,fragility:a.summary.fragility,contributors:a.summary.contributors}:null,recent:a.recent.slice(0,3).map(c=>({type:c.type,description:c.description,author:c.author,ts:c.ts})),co_changes:a.co_changes.slice(0,5)})),summary:{total_symbols:n.length,with_history:i.filter(a=>a.summary).length,fragile_count:i.filter(a=>a.summary?.fragility==="high"||a.summary?.fragility==="critical").length}};return {handled:true,text:JSON.stringify(o,null,2)}}case "paradigm_history_record":{let{type:n,symbols:r,intent:i,description:o,commit:a,files:c,reason:l}=e,d=await f(s.rootDir,{type:n,symbols:r,author:{type:"agent",id:"claude"},intent:i,description:o,commit:a,files:c,reason:l});return {handled:true,text:JSON.stringify({success:true,id:d,type:n,symbols:r,message:"History entry recorded successfully",note:"Run paradigm history reindex to update the index after multiple entries"})}}case "paradigm_history_validate":{let{implementation_id:n,result:r,tests:i}=e,o=await g$1(s.rootDir,n||"unknown",r,i);return {handled:true,text:JSON.stringify({success:true,id:o,result:r,tests:i,message:"Validation recorded successfully"})}}case "paradigm_history_fragility":{let{symbols:n}=e,r=await k$1(s),i=e$1(r,n);return {handled:true,text:JSON.stringify({symbols:n,safe_to_modify:i.safe_to_modify,fragile:i.fragile.map(o=>({symbol:o.symbol,fragility:o.fragility,reason:o.reason})),warnings:i.warnings,recommendations:i.recommendations,summary:i.fragile.length===0?"All symbols are stable - safe to proceed":i.safe_to_modify?"Some fragile symbols detected - proceed with extra testing":"Critical fragility detected - consider deferring changes or adding extensive tests"})}}default:return {handled:false,text:""}}}var It=null,$n=false;function ec(t){if(It||(It=new f$4),!$n)try{let e=r$3();for(let s of e)try{It.addPattern(s);}catch{}$n=!0;}catch{$n=true;}return It}function xi(){return [{name:"paradigm_sentinel_triage",description:"View and filter incidents with pattern matches. Returns recent errors with symbolic context and resolution suggestions. ~200-400 tokens depending on incident count.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter by symbol (e.g., @checkout, ^auth)"},status:{type:"string",enum:["open","investigating","resolved","wont-fix","all"],description:"Filter by status (default: all)"},environment:{type:"string",description:"Filter by environment"},search:{type:"string",description:"Search in error messages"},limit:{type:"number",description:"Max results (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_show",description:"Get full details of a specific incident including timeline and matched patterns. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID (e.g., INC-001)"},includeTimeline:{type:"boolean",description:"Include flow timeline"},includeSimilar:{type:"boolean",description:"Include similar incidents"}},required:["incidentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_resolve",description:"Mark an incident as resolved with optional pattern and commit reference. ~100 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID"},patternId:{type:"string",description:"Pattern that led to resolution"},commitHash:{type:"string",description:"Fix commit hash"},prUrl:{type:"string",description:"PR URL"},notes:{type:"string",description:"Resolution notes"},wontFix:{type:"boolean",description:"Mark as wont-fix instead of resolved"}},required:["incidentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_patterns",description:"List and filter failure patterns with confidence scores. Returns pattern names, match counts, and confidence scores. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter patterns for this symbol"},minConfidence:{type:"number",description:"Minimum confidence score"},source:{type:"string",enum:["manual","suggested","imported","community"],description:"Filter by source"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_add_pattern",description:"Create a new failure pattern. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Pattern ID (kebab-case)"},name:{type:"string",description:"Human-readable name"},description:{type:"string",description:"What this pattern matches"},pattern:{type:"object",properties:{symbols:{type:"object",description:"Symbol criteria"},errorContains:{type:"array",items:{type:"string"},description:"Error keywords"},missingSignals:{type:"array",items:{type:"string"},description:"Expected missing signals"}}},resolution:{type:"object",properties:{description:{type:"string",description:"Resolution steps"},strategy:{type:"string",enum:["retry","fallback","fix-data","fix-code","ignore","escalate"]},priority:{type:"string",enum:["low","medium","high","critical"]},codeHint:{type:"string",description:"Code fix hint"}},required:["description","strategy"]},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"}},required:["id","name","pattern","resolution"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_record",description:"Manually record a new incident. ~100 tokens.",inputSchema:{type:"object",properties:{error:{type:"object",properties:{message:{type:"string",description:"Error message"},stack:{type:"string",description:"Stack trace"},code:{type:"string",description:"Error code"},type:{type:"string",description:"Error type"}},required:["message"]},symbols:{type:"object",properties:{feature:{type:"string"},component:{type:"string"},flow:{type:"string"},gate:{type:"string"},signal:{type:"string"},state:{type:"string"},integration:{type:"string"}}},environment:{type:"string",description:"Environment (required)"},service:{type:"string",description:"Service name"},version:{type:"string",description:"App version"},flowPosition:{type:"object",properties:{flowId:{type:"string"},expected:{type:"array",items:{type:"string"}},actual:{type:"array",items:{type:"string"}},missing:{type:"array",items:{type:"string"}},failedAt:{type:"string"}}}},required:["error","symbols","environment"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_stats",description:"Get statistics and health metrics. Returns open/resolved counts, MTTR, and symbol breakdown. ~150 tokens.",inputSchema:{type:"object",properties:{period:{type:"string",description:"Period: 1d, 7d, 30d, 90d (default: 7d)"},symbol:{type:"string",description:"Get health for specific symbol"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_suggest_pattern",description:"Get AI suggestions for patterns based on incidents. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Suggest from specific incident"},minOccurrences:{type:"number",description:"Min similar incidents for suggestion"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_logs",description:"Query structured logs from connected apps. Filters by level, symbol, service, search text, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{level:{type:"string",enum:["debug","info","warn","error"],description:"Filter by log level"},symbol:{type:"string",description:"Filter by symbol (partial match)"},service:{type:"string",description:"Filter by service name"},search:{type:"string",description:"Search in log messages"},since:{type:"string",description:"ISO timestamp \u2014 logs after this time"},sessionId:{type:"string",description:"Filter by session ID"},correlationId:{type:"string",description:"Filter by correlation ID"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_services",description:"List all registered services with version, environment, and last-seen time. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_app_state",description:"Get live app state snapshots. Shows current state, active flows, and held gates for connected services. ~200 tokens.",inputSchema:{type:"object",properties:{service:{type:"string",description:"Filter by service name"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_validate_symbol",description:"Check if a symbol exists in the project index. Returns known/unknown status with suggestions for typos. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to validate (e.g., #checkout, ^auth)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_flow_activity",description:"Get recent flow events \u2014 which flow nodes were hit, in what order, by which service. ~200 tokens.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Filter by flow ID (e.g., $checkout-flow)"},service:{type:"string",description:"Filter by service name"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_metrics",description:"Query metrics (counters, gauges, histograms) from connected apps. Supports filtering and aggregation. ~200 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Metric name filter"},type:{type:"string",enum:["counter","gauge","histogram"],description:"Metric type filter"},service:{type:"string",description:"Service name filter"},since:{type:"string",description:"ISO timestamp \u2014 metrics after this time"},aggregate:{type:"boolean",description:"If true and name is provided, return aggregation (count/sum/min/max/avg) instead of raw data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_traces",description:"Query distributed traces across services. Shows span trees with timing, status, and service hops. ~200 tokens.",inputSchema:{type:"object",properties:{traceId:{type:"string",description:"Get a specific trace by ID"},service:{type:"string",description:"Filter by service name"},symbol:{type:"string",description:"Filter by symbol"},since:{type:"string",description:"ISO timestamp \u2014 traces after this time"},limit:{type:"number",description:"Max traces (default: 10, max: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_schemas",description:"List or get registered event schemas. Schemas define event types, scopes, causality, and visualization for application-agnostic observability. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Get a specific schema by ID. Omit to list all."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_events",description:"Query generic events from any registered schema. Filters by schema, event type, category, scope, service, severity, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:'Filter by schema ID (e.g., "pretend-engine")'},eventType:{type:"string",description:'Filter by event type (e.g., "rule:fire")'},category:{type:"string",description:'Filter by category (e.g., "rules")'},service:{type:"string",description:"Filter by service name"},scopeValue:{type:"string",description:"Filter by scope value (e.g., frame number)"},severity:{type:"string",enum:["debug","info","warn","error"],description:"Filter by severity"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"},search:{type:"string",description:"Full-text search in event data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_scopes",description:"Get scope summaries for a schema \u2014 e.g., frame list with event counts, request list with category breakdown. ~200 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:"Schema ID (required)"},sessionId:{type:"string",description:"Filter by session ID"},limit:{type:"number",description:"Max scopes (default: 50)"}},required:["schemaId"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ci(t,e,s){let n=ec(),r=new o$2(n);switch(t){case "paradigm_sentinel_triage":{let{symbol:i,status:o="all",environment:a,search:c,limit:l=10}=e,d=n.getRecentIncidents({limit:l,status:o,symbol:i,environment:a,search:c});if(d.length===0)return {handled:true,text:JSON.stringify({count:0,incidents:[],tip:"No incidents recorded yet. Incidents are created when errors occur in production or via paradigm_sentinel_record.",howToRecord:{description:"Record incidents manually with paradigm_sentinel_record",example:{error:{message:"Connection timeout",code:"ETIMEDOUT"},symbols:{feature:"@checkout",integration:"&stripe"},environment:"production"}}},null,2)};let u=d.map(p=>{let g=r.match(p,{maxResults:3});return {id:p.id,timestamp:p.timestamp,status:p.status,error:p.error.message,symbols:p.symbols,environment:p.environment,matches:g.map(m=>({patternId:m.pattern.id,name:m.pattern.name,confidence:m.confidence,strategy:m.pattern.resolution.strategy,description:m.pattern.resolution.description}))}});return {handled:true,text:JSON.stringify({count:u.length,incidents:u},null,2)}}case "paradigm_sentinel_show":{let{incidentId:i,includeTimeline:o,includeSimilar:a}=e,c=n.getIncident(i);if(!c)return {handled:true,text:JSON.stringify({error:`Incident ${i} not found`})};let l=r.match(c,{maxResults:5}),d={incident:c,matches:l.map(u=>({patternId:u.pattern.id,name:u.pattern.name,confidence:u.confidence,matchedCriteria:u.matchedCriteria,resolution:u.pattern.resolution}))};if(o&&c.flowPosition){let u=new x().build(c);u&&(d.timeline=new x().renderStructured(u));}if(a){let u=n.getRecentIncidents({symbol:Object.values(c.symbols)[0],limit:5}).filter(p=>p.id!==i);d.similar=u.map(p=>({id:p.id,error:p.error.message,status:p.status}));}return {handled:true,text:JSON.stringify(d,null,2)}}case "paradigm_sentinel_resolve":{let{incidentId:i,patternId:o,commitHash:a,prUrl:c,notes:l,wontFix:d}=e;return n.getIncident(i)?d?(n.updateIncident(i,{status:"wont-fix",resolvedAt:new Date().toISOString(),resolvedBy:"manual",resolution:{notes:l}}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${i} marked as won't fix`})}):(n.recordResolution({incidentId:i,patternId:o,commitHash:a,prUrl:c,notes:l}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${i} resolved`,patternId:o,commitHash:a,prUrl:c})}):{handled:true,text:JSON.stringify({error:`Incident ${i} not found`})}}case "paradigm_sentinel_patterns":{let{symbol:i,minConfidence:o,source:a}=e,c=n.getAllPatterns({source:a,minConfidence:o,includePrivate:false}),l=c;return i&&(l=c.filter(d=>{let u=d.pattern.symbols;return Object.values(u).some(p=>p?Array.isArray(p)?p.includes(i)||p.some(g=>i.match(g.replace("*",".*"))):p===i||i.match(p.replace("*",".*")):false)})),{handled:true,text:JSON.stringify({count:l.length,patterns:l.map(d=>({id:d.id,name:d.name,description:d.description,confidence:d.confidence.score,resolution:d.resolution,tags:d.tags}))},null,2)}}case "paradigm_sentinel_add_pattern":{let{id:i,name:o,description:a,pattern:c,resolution:l,tags:d}=e,u={id:i,name:o,description:a||"",pattern:{symbols:c.symbols||{},errorContains:c.errorContains,missingSignals:c.missingSignals},resolution:{description:l.description,strategy:l.strategy,priority:l.priority||"medium",codeHint:l.codeHint},source:"manual",private:false,tags:d||[]};return n.addPattern(u),{handled:true,text:JSON.stringify({success:true,message:`Pattern ${i} created`,pattern:u})}}case "paradigm_sentinel_record":{let{error:i,symbols:o,environment:a,service:c,version:l,flowPosition:d}=e,u=n.recordIncident({error:i,symbols:o,environment:a,service:c,version:l,flowPosition:d}),p=n.getIncident(u),g=p?r.match(p,{maxResults:3}):[];return {handled:true,text:JSON.stringify({success:true,incidentId:u,matches:g.map(m=>({patternId:m.pattern.id,confidence:m.confidence,resolution:m.pattern.resolution.description}))},null,2)}}case "paradigm_sentinel_stats":{let{period:i="7d",symbol:o}=e,a=new y(n);if(o){let u=a.getSymbolHealth(o);return {handled:true,text:JSON.stringify({symbol:o,health:u},null,2)}}let c=i.match(/^(\d+)d$/),l=c?parseInt(c[1],10):7,d=a.getStats(l);return {handled:true,text:JSON.stringify({period:`${l}d`,stats:d},null,2)}}case "paradigm_sentinel_suggest_pattern":{let{incidentId:i,minOccurrences:o}=e,a=new A$2(n);if(i){let l=n.getIncident(i);if(!l)return {handled:true,text:JSON.stringify({error:`Incident ${i} not found`})};let d=a.suggestFromIncident(l);return {handled:true,text:JSON.stringify({source:"incident",incidentId:i,suggestion:d},null,2)}}let c=a.findPatternCandidates(o||3);return {handled:true,text:JSON.stringify({source:"analysis",candidates:c.slice(0,5).map(l=>({occurrences:l.occurrenceCount,sampleIncidents:l.incidents.slice(0,3).map(d=>d.id),suggestion:l.suggestedPattern}))},null,2)}}case "paradigm_sentinel_logs":{let{level:i,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:u,limit:p=50}=e,g=n.queryLogs({level:i,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:u,limit:p}),m=n.getLogCount({level:i,symbol:o,service:a,since:l});return {handled:true,text:JSON.stringify({count:g.length,total:m,logs:g.map(y=>({timestamp:y.timestamp,level:y.level,symbol:y.symbol,service:y.service,message:y.message,data:y.data,sessionId:y.sessionId,correlationId:y.correlationId,durationMs:y.durationMs}))},null,2)}}case "paradigm_sentinel_services":{let i=n.getServices();return {handled:true,text:JSON.stringify({count:i.length,services:i.map(o=>({name:o.name,version:o.version,environment:o.environment,lastSeen:o.lastSeenAt,startedAt:o.startedAt,pid:o.pid}))},null,2)}}case "paradigm_sentinel_app_state":{let{service:i}=e,o=i?n.getAppState(i):n.getAllAppStates();return {handled:true,text:JSON.stringify({states:o.map(a=>({service:a.service,sessionId:a.sessionId,state:a.state,activeFlows:a.activeFlows,activeGates:a.activeGates,timestamp:a.timestamp}))},null,2)}}case "paradigm_sentinel_validate_symbol":{let{symbol:i}=e,o=n.getLogCount({symbol:i});return {handled:true,text:JSON.stringify({symbol:i,usedInLogs:o>0,logCount:o,tip:o===0?"This symbol has not appeared in any logs. It may be a typo or unused.":`This symbol has been used in ${o} log entries.`},null,2)}}case "paradigm_sentinel_flow_activity":{let{flowId:i,service:o,since:a}=e,l=n.queryLogs({symbol:i,service:o,since:a,limit:100}).filter(d=>["flow","signal","gate"].includes(d.symbolType)).map(d=>({timestamp:d.timestamp,symbol:d.symbol,symbolType:d.symbolType,service:d.service,message:d.message,level:d.level}));return {handled:true,text:JSON.stringify({count:l.length,events:l},null,2)}}case "paradigm_sentinel_metrics":{let{name:i,type:o,service:a,since:c,aggregate:l,limit:d}=e;if(l&&i){let p=n.aggregateMetric(i,{service:a,since:c});return {handled:true,text:JSON.stringify(p,null,2)}}let u=n.queryMetrics({name:i,type:o,service:a,since:c,limit:Math.min(d||50,100)});return {handled:true,text:JSON.stringify({count:u.length,metrics:u.map(p=>({timestamp:p.timestamp,name:p.name,type:p.type,value:p.value,tags:p.tags,service:p.service}))},null,2)}}case "paradigm_sentinel_traces":{let{traceId:i,service:o,symbol:a,since:c,limit:l}=e;if(i){let u=n.getTrace(i);return u?{handled:true,text:JSON.stringify(u,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let d=n.queryTraces({service:o,symbol:a,since:c,limit:Math.min(l||10,20)});return {handled:true,text:JSON.stringify({count:d.length,traces:d.map(u=>({traceId:u.traceId,services:u.services,spanCount:u.spans.length,totalDurationMs:u.totalDurationMs,startTime:u.startTime,endTime:u.endTime}))},null,2)}}case "paradigm_sentinel_schemas":{let{id:i}=e;if(i){let a=n.getSchema(i);return a?{handled:true,text:JSON.stringify(a,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${i}" not found`})}}let o=n.listSchemas();return o.length===0?{handled:true,text:JSON.stringify({count:0,schemas:[],tip:"No event schemas registered yet. Applications register schemas via POST /api/schemas or SentinelWebClient.registerSchema()."},null,2)}:{handled:true,text:JSON.stringify({count:o.length,schemas:o.map(a=>({id:a.id,version:a.version,name:a.name,description:a.description,eventTypeCount:a.eventTypes.length,scope:a.scope.label,tags:a.tags,registeredAt:a.registeredAt}))},null,2)}}case "paradigm_sentinel_events":{let{schemaId:i,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:u,search:p,limit:g}=e,m=n.queryEvents({schemaId:i,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:u,search:p,limit:Math.min(g||50,100)});return m.length===0?{handled:true,text:JSON.stringify({count:0,events:[],tip:"No events found. Events are ingested via POST /api/events or SentinelWebClient.emit()."},null,2)}:{handled:true,text:JSON.stringify({count:m.length,events:m.map(y=>({id:y.id,schemaId:y.schemaId,eventType:y.eventType,category:y.category,timestamp:y.timestamp,scopeValue:y.scopeValue,service:y.service,severity:y.severity,data:y.data,parentEventId:y.parentEventId,depth:y.depth}))},null,2)}}case "paradigm_sentinel_scopes":{let{schemaId:i,sessionId:o,limit:a}=e,c=n.getEventScopes(i,{limit:Math.min(a||50,200),sessionId:o});return c.length===0?{handled:true,text:JSON.stringify({count:0,scopes:[],tip:`No scopes found for schema "${i}". Events with scope values are required.`},null,2)}:{handled:true,text:JSON.stringify({count:c.length,scopes:c},null,2)}}default:return {handled:false,text:""}}}function Ri(){return [{name:"paradigm_flows_affected",description:"Find flows affected by changes to a symbol. Returns flows that include the symbol in their steps, with downstream impact analysis and validation commands. Returns flow IDs, step positions, and validation commands. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol being modified (e.g., @tasks, ^project-member, !task-created)"},includeValidation:{type:"boolean",description:"Include validation commands in response (default: true)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_flow_check",description:"Check flow definition completeness \u2014 verifies that gates referenced in flows.yaml exist in portal.yaml and that required fields are present. Does not trace code execution paths.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Specific flow ID to validate (e.g., $task-creation). If not provided, validates all flows."},checkImplementation:{type:"boolean",description:"Deep check: verify actions and signals exist in codebase (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Pi(t,e,s){switch(t){case "paradigm_flows_affected":{let{symbol:n,includeValidation:r=true}=e,i=await o$3(s.rootDir);if(!i)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:n,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
2
+ import {n as n$4,j as j$2,P,O as O$1,K,Q as Q$1,L,I as I$1,J as J$1,D as D$1,H as H$2,m as m$3,l as l$3,E,v as v$2,N,q as q$2,C as C$1,S as S$1,o as o$4,z as z$3,t as t$1,B as B$1,s as s$2}from'./chunk-ZUAUFZRJ.js';import {b as b$3,c as c$1}from'./chunk-YQK3XU63.js';import {n as n$1,h,l as l$1,q as q$1,C,s,A,u,m as m$1,r,D,t,B,v as v$1,k as k$1,e as e$1,g,f as f$1,c as c$2,o as o$3,p as p$1,x as x$2,y as y$3,w as w$1,z as z$5}from'./chunk-OIYJUU6T.js';import {a as a$3,n as n$3,o as o$1,c as c$6,d as d$9,l as l$5,k as k$3,e as e$a,i as i$3,f as f$5,g as g$4,h as h$6,m as m$4,j as j$3,b as b$d}from'./chunk-VPNJL4LS.js';import {Q,T,O,a as a$2,H as H$1,R,S,c as c$5,l as l$2,k as k$2,i,m as m$2,b as b$8,h as h$3,g as g$2,f as f$3,e as e$5,d as d$5,A as A$2,r as r$2,z as z$4,t as t$2,v as v$3,x as x$1,w,B as B$2,y as y$1,u as u$1,s as s$3,E as E$1,C as C$2,o as o$5,q as q$3}from'./chunk-KP5VOYAH.js';import {a as a$5,b as b$5}from'./chunk-B5KLSBOZ.js';import {a as a$1,b as b$2}from'./chunk-4UJ4NIEQ.js';import {a as a$4,b as b$4}from'./chunk-HSY75GRR.js';import {e,v,n,c as c$3,d}from'./chunk-RVXQNS6K.js';import {j,h as h$5,g as g$3,e as e$7,b as b$a}from'./chunk-KAUGQMXU.js';import {h as h$1,e as e$2,a as a$7,d as d$1}from'./chunk-Q527BPUF.js';import {a as a$6,b as b$b,d as d$7,e as e$8}from'./chunk-RGSFU2YW.js';import {l,p,k,n as n$2,o,m,q,r as r$1,s as s$1,b as b$c,e as e$9,d as d$8,t as t$3,c as c$7,h as h$7}from'./chunk-TMDPDIWA.js';import {o as o$2,A as A$1,y,x,f as f$4,r as r$3}from'./chunk-KLBH26PA.js';import {i as i$2}from'./chunk-XROULIQN.js';import {z as z$2,h as h$4,b as b$9,d as d$6,e as e$6,i as i$1,y as y$2,l as l$4}from'./chunk-KAFQA7HV.js';import {j as j$1}from'./chunk-ACJWUOMA.js';import {h as h$2,d as d$4,g as g$1,f as f$2,c as c$4,e as e$4}from'./chunk-CHSU6LTR.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {d as d$3,b as b$7,a as a$9}from'./chunk-JNSJVCTU.js';import {f,e as e$3,b as b$6,d as d$2,a as a$8}from'./chunk-ECO3LHCE.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as I from'fs';import*as $ from'path';import*as qe from'js-yaml';import*as Ni from'os';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import*as ct from'crypto';import {execSync}from'child_process';import {z as z$1}from'zod';import*as Qe from'fs/promises';var dt,Mn,Gn=b(()=>{dt={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"]},Mn=new Set(["tool-called","context-checked"]);});var Yi={};c(Yi,{getAllStates:()=>Un,getConfig:()=>Le,getState:()=>Ut,incrementFailure:()=>Vi,invalidateGraduationCache:()=>Uc,isGraduated:()=>Gc,loadGraduation:()=>Oe,markNeverGraduate:()=>Jc,saveGraduation:()=>Jt,setTier:()=>Bi});function zi(t){return $.join(t,".paradigm","graduation.yaml")}function Oe(t){let e=$.resolve(t);if(pt&&Lt===e&&Date.now()-Mt<Mc)return pt;let s=zi(e),n;if(I.existsSync(s))try{let r=I.readFileSync(s,"utf8");n=qe.load(r);}catch{n={version:"1.0",config:{},states:{}};}else n={version:"1.0",config:{},states:{}};return n.version||(n.version="1.0"),n.config||(n.config={}),n.states||(n.states={}),pt=n,Lt=e,Mt=Date.now(),n}function Jt(t,e){let s=$.resolve(t),n=zi(s),r=$.dirname(n);I.existsSync(r)||I.mkdirSync(r,{recursive:true});let i=qe.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});I.writeFileSync(n,i,"utf8"),pt=e,Lt=s,Mt=Date.now();}function Le(t){let e=Oe(t);return {...dt,...e.config,thresholds:{...dt.thresholds,...e.config?.thresholds},demotion:{...dt.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??dt.neverGraduate}}function Jn(t){return {habitId:t,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Ut(t,e){let n=Oe(t).states[e];return n?{...Jn(e),...n,habitId:e}:Jn(e)}function Un(t){let e=Oe(t),s={};for(let[n,r]of Object.entries(e.states))s[n]={...Jn(n),...r,habitId:n};return s}function Gc(t,e){return Ut(t,e).tier==="hook"}function Bi(t,e,s,n){let r=Oe(t),i=r.states[e]||{};r.states[e]={...i,tier:s,previousTier:i.tier||"habit",...s==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...s==="habit"&&i.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...n},Jt(t,r);}function Jc(t,e){let s=Oe(t);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",Jt(t,s);}function Vi(t,e){let s=Oe(t);s.states[e]||(s.states[e]={});let n=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=n,Jt(t,s),n}function Uc(){pt=null,Lt=null,Mt=0;}var pt,Lt,Mt,Mc,Wt=b(()=>{Gn();pt=null,Lt=null,Mt=0,Mc=3e4;});function _i(){return [{name:"paradigm_history_context",description:"Get implementation history for symbols before modifying. Shows recent changes, stability, and who has worked on these areas. Returns recent commits, authors, and change frequency. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get history for (e.g., ["@checkout", "#payment-form"])'}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_history_record",description:"Record an implementation event (feature, fix, refactor). Call this after making changes to track what was done. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["implement","refactor","rollback"],description:"Type of change"},symbols:{type:"array",items:{type:"string"},description:"Symbols affected by this change"},intent:{type:"string",enum:["feature","fix","refactor","experimental","confirmed"],description:"Intent of the change"},description:{type:"string",description:"What was done"},commit:{type:"string",description:"Git commit hash (optional)"},files:{type:"array",items:{type:"string"},description:"Files affected (optional)"},reason:{type:"string",description:"Reason for rollback (if type is rollback)"}},required:["type","symbols","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_validate",description:"Record a validation result (tests passed/failed). Call this after running tests. ~100 tokens.",inputSchema:{type:"object",properties:{implementation_id:{type:"string",description:"ID of the implementation being validated (from paradigm_history_record)"},result:{type:"string",enum:["pass","fail","partial"],description:"Validation result"},tests:{type:"object",properties:{passed:{type:"number"},failed:{type:"number"},skipped:{type:"number"}},description:"Test counts"}},required:["result"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_fragility",description:"Check fragility of symbols before modifying. Returns stability scores and warnings for fragile areas. Returns numeric stability scores (0-100) and actionable warnings. ~150 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols to check fragility for"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Si(t,e,s){switch(t){case "paradigm_history_context":{let{symbols:n}=e,r=await k$1(s),i=c$2(r,n),o={symbols:n,history:i.map(a=>({symbol:a.symbol,summary:a.summary?{total_changes:a.summary.total_changes,last_modified:a.summary.last_modified,stability_score:a.summary.stability_score,fragility:a.summary.fragility,contributors:a.summary.contributors}:null,recent:a.recent.slice(0,3).map(c=>({type:c.type,description:c.description,author:c.author,ts:c.ts})),co_changes:a.co_changes.slice(0,5)})),summary:{total_symbols:n.length,with_history:i.filter(a=>a.summary).length,fragile_count:i.filter(a=>a.summary?.fragility==="high"||a.summary?.fragility==="critical").length}};return {handled:true,text:JSON.stringify(o,null,2)}}case "paradigm_history_record":{let{type:n,symbols:r,intent:i,description:o,commit:a,files:c,reason:l}=e,d=await f$1(s.rootDir,{type:n,symbols:r,author:{type:"agent",id:"claude"},intent:i,description:o,commit:a,files:c,reason:l});return {handled:true,text:JSON.stringify({success:true,id:d,type:n,symbols:r,message:"History entry recorded successfully",note:"Run paradigm history reindex to update the index after multiple entries"})}}case "paradigm_history_validate":{let{implementation_id:n,result:r,tests:i}=e,o=await g(s.rootDir,n||"unknown",r,i);return {handled:true,text:JSON.stringify({success:true,id:o,result:r,tests:i,message:"Validation recorded successfully"})}}case "paradigm_history_fragility":{let{symbols:n}=e,r=await k$1(s),i=e$1(r,n);return {handled:true,text:JSON.stringify({symbols:n,safe_to_modify:i.safe_to_modify,fragile:i.fragile.map(o=>({symbol:o.symbol,fragility:o.fragility,reason:o.reason})),warnings:i.warnings,recommendations:i.recommendations,summary:i.fragile.length===0?"All symbols are stable - safe to proceed":i.safe_to_modify?"Some fragile symbols detected - proceed with extra testing":"Critical fragility detected - consider deferring changes or adding extensive tests"})}}default:return {handled:false,text:""}}}var It=null,$n=false;function ec(t){if(It||(It=new f$4),!$n)try{let e=r$3();for(let s of e)try{It.addPattern(s);}catch{}$n=!0;}catch{$n=true;}return It}function xi(){return [{name:"paradigm_sentinel_triage",description:"View and filter incidents with pattern matches. Returns recent errors with symbolic context and resolution suggestions. ~200-400 tokens depending on incident count.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter by symbol (e.g., @checkout, ^auth)"},status:{type:"string",enum:["open","investigating","resolved","wont-fix","all"],description:"Filter by status (default: all)"},environment:{type:"string",description:"Filter by environment"},search:{type:"string",description:"Search in error messages"},limit:{type:"number",description:"Max results (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_show",description:"Get full details of a specific incident including timeline and matched patterns. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID (e.g., INC-001)"},includeTimeline:{type:"boolean",description:"Include flow timeline"},includeSimilar:{type:"boolean",description:"Include similar incidents"}},required:["incidentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_resolve",description:"Mark an incident as resolved with optional pattern and commit reference. ~100 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID"},patternId:{type:"string",description:"Pattern that led to resolution"},commitHash:{type:"string",description:"Fix commit hash"},prUrl:{type:"string",description:"PR URL"},notes:{type:"string",description:"Resolution notes"},wontFix:{type:"boolean",description:"Mark as wont-fix instead of resolved"}},required:["incidentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_patterns",description:"List and filter failure patterns with confidence scores. Returns pattern names, match counts, and confidence scores. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter patterns for this symbol"},minConfidence:{type:"number",description:"Minimum confidence score"},source:{type:"string",enum:["manual","suggested","imported","community"],description:"Filter by source"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_add_pattern",description:"Create a new failure pattern. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Pattern ID (kebab-case)"},name:{type:"string",description:"Human-readable name"},description:{type:"string",description:"What this pattern matches"},pattern:{type:"object",properties:{symbols:{type:"object",description:"Symbol criteria"},errorContains:{type:"array",items:{type:"string"},description:"Error keywords"},missingSignals:{type:"array",items:{type:"string"},description:"Expected missing signals"}}},resolution:{type:"object",properties:{description:{type:"string",description:"Resolution steps"},strategy:{type:"string",enum:["retry","fallback","fix-data","fix-code","ignore","escalate"]},priority:{type:"string",enum:["low","medium","high","critical"]},codeHint:{type:"string",description:"Code fix hint"}},required:["description","strategy"]},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"}},required:["id","name","pattern","resolution"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_record",description:"Manually record a new incident. ~100 tokens.",inputSchema:{type:"object",properties:{error:{type:"object",properties:{message:{type:"string",description:"Error message"},stack:{type:"string",description:"Stack trace"},code:{type:"string",description:"Error code"},type:{type:"string",description:"Error type"}},required:["message"]},symbols:{type:"object",properties:{feature:{type:"string"},component:{type:"string"},flow:{type:"string"},gate:{type:"string"},signal:{type:"string"},state:{type:"string"},integration:{type:"string"}}},environment:{type:"string",description:"Environment (required)"},service:{type:"string",description:"Service name"},version:{type:"string",description:"App version"},flowPosition:{type:"object",properties:{flowId:{type:"string"},expected:{type:"array",items:{type:"string"}},actual:{type:"array",items:{type:"string"}},missing:{type:"array",items:{type:"string"}},failedAt:{type:"string"}}}},required:["error","symbols","environment"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_stats",description:"Get statistics and health metrics. Returns open/resolved counts, MTTR, and symbol breakdown. ~150 tokens.",inputSchema:{type:"object",properties:{period:{type:"string",description:"Period: 1d, 7d, 30d, 90d (default: 7d)"},symbol:{type:"string",description:"Get health for specific symbol"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_suggest_pattern",description:"Get AI suggestions for patterns based on incidents. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Suggest from specific incident"},minOccurrences:{type:"number",description:"Min similar incidents for suggestion"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_logs",description:"Query structured logs from connected apps. Filters by level, symbol, service, search text, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{level:{type:"string",enum:["debug","info","warn","error"],description:"Filter by log level"},symbol:{type:"string",description:"Filter by symbol (partial match)"},service:{type:"string",description:"Filter by service name"},search:{type:"string",description:"Search in log messages"},since:{type:"string",description:"ISO timestamp \u2014 logs after this time"},sessionId:{type:"string",description:"Filter by session ID"},correlationId:{type:"string",description:"Filter by correlation ID"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_services",description:"List all registered services with version, environment, and last-seen time. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_app_state",description:"Get live app state snapshots. Shows current state, active flows, and held gates for connected services. ~200 tokens.",inputSchema:{type:"object",properties:{service:{type:"string",description:"Filter by service name"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_validate_symbol",description:"Check if a symbol exists in the project index. Returns known/unknown status with suggestions for typos. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to validate (e.g., #checkout, ^auth)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_flow_activity",description:"Get recent flow events \u2014 which flow nodes were hit, in what order, by which service. ~200 tokens.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Filter by flow ID (e.g., $checkout-flow)"},service:{type:"string",description:"Filter by service name"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_metrics",description:"Query metrics (counters, gauges, histograms) from connected apps. Supports filtering and aggregation. ~200 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Metric name filter"},type:{type:"string",enum:["counter","gauge","histogram"],description:"Metric type filter"},service:{type:"string",description:"Service name filter"},since:{type:"string",description:"ISO timestamp \u2014 metrics after this time"},aggregate:{type:"boolean",description:"If true and name is provided, return aggregation (count/sum/min/max/avg) instead of raw data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_traces",description:"Query distributed traces across services. Shows span trees with timing, status, and service hops. ~200 tokens.",inputSchema:{type:"object",properties:{traceId:{type:"string",description:"Get a specific trace by ID"},service:{type:"string",description:"Filter by service name"},symbol:{type:"string",description:"Filter by symbol"},since:{type:"string",description:"ISO timestamp \u2014 traces after this time"},limit:{type:"number",description:"Max traces (default: 10, max: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_schemas",description:"List or get registered event schemas. Schemas define event types, scopes, causality, and visualization for application-agnostic observability. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Get a specific schema by ID. Omit to list all."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_events",description:"Query generic events from any registered schema. Filters by schema, event type, category, scope, service, severity, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:'Filter by schema ID (e.g., "pretend-engine")'},eventType:{type:"string",description:'Filter by event type (e.g., "rule:fire")'},category:{type:"string",description:'Filter by category (e.g., "rules")'},service:{type:"string",description:"Filter by service name"},scopeValue:{type:"string",description:"Filter by scope value (e.g., frame number)"},severity:{type:"string",enum:["debug","info","warn","error"],description:"Filter by severity"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"},search:{type:"string",description:"Full-text search in event data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_scopes",description:"Get scope summaries for a schema \u2014 e.g., frame list with event counts, request list with category breakdown. ~200 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:"Schema ID (required)"},sessionId:{type:"string",description:"Filter by session ID"},limit:{type:"number",description:"Max scopes (default: 50)"}},required:["schemaId"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ci(t,e,s){let n=ec(),r=new o$2(n);switch(t){case "paradigm_sentinel_triage":{let{symbol:i,status:o="all",environment:a,search:c,limit:l=10}=e,d=n.getRecentIncidents({limit:l,status:o,symbol:i,environment:a,search:c});if(d.length===0)return {handled:true,text:JSON.stringify({count:0,incidents:[],tip:"No incidents recorded yet. Incidents are created when errors occur in production or via paradigm_sentinel_record.",howToRecord:{description:"Record incidents manually with paradigm_sentinel_record",example:{error:{message:"Connection timeout",code:"ETIMEDOUT"},symbols:{feature:"@checkout",integration:"&stripe"},environment:"production"}}},null,2)};let u=d.map(p=>{let g=r.match(p,{maxResults:3});return {id:p.id,timestamp:p.timestamp,status:p.status,error:p.error.message,symbols:p.symbols,environment:p.environment,matches:g.map(m=>({patternId:m.pattern.id,name:m.pattern.name,confidence:m.confidence,strategy:m.pattern.resolution.strategy,description:m.pattern.resolution.description}))}});return {handled:true,text:JSON.stringify({count:u.length,incidents:u},null,2)}}case "paradigm_sentinel_show":{let{incidentId:i,includeTimeline:o,includeSimilar:a}=e,c=n.getIncident(i);if(!c)return {handled:true,text:JSON.stringify({error:`Incident ${i} not found`})};let l=r.match(c,{maxResults:5}),d={incident:c,matches:l.map(u=>({patternId:u.pattern.id,name:u.pattern.name,confidence:u.confidence,matchedCriteria:u.matchedCriteria,resolution:u.pattern.resolution}))};if(o&&c.flowPosition){let u=new x().build(c);u&&(d.timeline=new x().renderStructured(u));}if(a){let u=n.getRecentIncidents({symbol:Object.values(c.symbols)[0],limit:5}).filter(p=>p.id!==i);d.similar=u.map(p=>({id:p.id,error:p.error.message,status:p.status}));}return {handled:true,text:JSON.stringify(d,null,2)}}case "paradigm_sentinel_resolve":{let{incidentId:i,patternId:o,commitHash:a,prUrl:c,notes:l,wontFix:d}=e;return n.getIncident(i)?d?(n.updateIncident(i,{status:"wont-fix",resolvedAt:new Date().toISOString(),resolvedBy:"manual",resolution:{notes:l}}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${i} marked as won't fix`})}):(n.recordResolution({incidentId:i,patternId:o,commitHash:a,prUrl:c,notes:l}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${i} resolved`,patternId:o,commitHash:a,prUrl:c})}):{handled:true,text:JSON.stringify({error:`Incident ${i} not found`})}}case "paradigm_sentinel_patterns":{let{symbol:i,minConfidence:o,source:a}=e,c=n.getAllPatterns({source:a,minConfidence:o,includePrivate:false}),l=c;return i&&(l=c.filter(d=>{let u=d.pattern.symbols;return Object.values(u).some(p=>p?Array.isArray(p)?p.includes(i)||p.some(g=>i.match(g.replace("*",".*"))):p===i||i.match(p.replace("*",".*")):false)})),{handled:true,text:JSON.stringify({count:l.length,patterns:l.map(d=>({id:d.id,name:d.name,description:d.description,confidence:d.confidence.score,resolution:d.resolution,tags:d.tags}))},null,2)}}case "paradigm_sentinel_add_pattern":{let{id:i,name:o,description:a,pattern:c,resolution:l,tags:d}=e,u={id:i,name:o,description:a||"",pattern:{symbols:c.symbols||{},errorContains:c.errorContains,missingSignals:c.missingSignals},resolution:{description:l.description,strategy:l.strategy,priority:l.priority||"medium",codeHint:l.codeHint},source:"manual",private:false,tags:d||[]};return n.addPattern(u),{handled:true,text:JSON.stringify({success:true,message:`Pattern ${i} created`,pattern:u})}}case "paradigm_sentinel_record":{let{error:i,symbols:o,environment:a,service:c,version:l,flowPosition:d}=e,u=n.recordIncident({error:i,symbols:o,environment:a,service:c,version:l,flowPosition:d}),p=n.getIncident(u),g=p?r.match(p,{maxResults:3}):[];return {handled:true,text:JSON.stringify({success:true,incidentId:u,matches:g.map(m=>({patternId:m.pattern.id,confidence:m.confidence,resolution:m.pattern.resolution.description}))},null,2)}}case "paradigm_sentinel_stats":{let{period:i="7d",symbol:o}=e,a=new y(n);if(o){let u=a.getSymbolHealth(o);return {handled:true,text:JSON.stringify({symbol:o,health:u},null,2)}}let c=i.match(/^(\d+)d$/),l=c?parseInt(c[1],10):7,d=a.getStats(l);return {handled:true,text:JSON.stringify({period:`${l}d`,stats:d},null,2)}}case "paradigm_sentinel_suggest_pattern":{let{incidentId:i,minOccurrences:o}=e,a=new A$1(n);if(i){let l=n.getIncident(i);if(!l)return {handled:true,text:JSON.stringify({error:`Incident ${i} not found`})};let d=a.suggestFromIncident(l);return {handled:true,text:JSON.stringify({source:"incident",incidentId:i,suggestion:d},null,2)}}let c=a.findPatternCandidates(o||3);return {handled:true,text:JSON.stringify({source:"analysis",candidates:c.slice(0,5).map(l=>({occurrences:l.occurrenceCount,sampleIncidents:l.incidents.slice(0,3).map(d=>d.id),suggestion:l.suggestedPattern}))},null,2)}}case "paradigm_sentinel_logs":{let{level:i,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:u,limit:p=50}=e,g=n.queryLogs({level:i,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:u,limit:p}),m=n.getLogCount({level:i,symbol:o,service:a,since:l});return {handled:true,text:JSON.stringify({count:g.length,total:m,logs:g.map(y=>({timestamp:y.timestamp,level:y.level,symbol:y.symbol,service:y.service,message:y.message,data:y.data,sessionId:y.sessionId,correlationId:y.correlationId,durationMs:y.durationMs}))},null,2)}}case "paradigm_sentinel_services":{let i=n.getServices();return {handled:true,text:JSON.stringify({count:i.length,services:i.map(o=>({name:o.name,version:o.version,environment:o.environment,lastSeen:o.lastSeenAt,startedAt:o.startedAt,pid:o.pid}))},null,2)}}case "paradigm_sentinel_app_state":{let{service:i}=e,o=i?n.getAppState(i):n.getAllAppStates();return {handled:true,text:JSON.stringify({states:o.map(a=>({service:a.service,sessionId:a.sessionId,state:a.state,activeFlows:a.activeFlows,activeGates:a.activeGates,timestamp:a.timestamp}))},null,2)}}case "paradigm_sentinel_validate_symbol":{let{symbol:i}=e,o=n.getLogCount({symbol:i});return {handled:true,text:JSON.stringify({symbol:i,usedInLogs:o>0,logCount:o,tip:o===0?"This symbol has not appeared in any logs. It may be a typo or unused.":`This symbol has been used in ${o} log entries.`},null,2)}}case "paradigm_sentinel_flow_activity":{let{flowId:i,service:o,since:a}=e,l=n.queryLogs({symbol:i,service:o,since:a,limit:100}).filter(d=>["flow","signal","gate"].includes(d.symbolType)).map(d=>({timestamp:d.timestamp,symbol:d.symbol,symbolType:d.symbolType,service:d.service,message:d.message,level:d.level}));return {handled:true,text:JSON.stringify({count:l.length,events:l},null,2)}}case "paradigm_sentinel_metrics":{let{name:i,type:o,service:a,since:c,aggregate:l,limit:d}=e;if(l&&i){let p=n.aggregateMetric(i,{service:a,since:c});return {handled:true,text:JSON.stringify(p,null,2)}}let u=n.queryMetrics({name:i,type:o,service:a,since:c,limit:Math.min(d||50,100)});return {handled:true,text:JSON.stringify({count:u.length,metrics:u.map(p=>({timestamp:p.timestamp,name:p.name,type:p.type,value:p.value,tags:p.tags,service:p.service}))},null,2)}}case "paradigm_sentinel_traces":{let{traceId:i,service:o,symbol:a,since:c,limit:l}=e;if(i){let u=n.getTrace(i);return u?{handled:true,text:JSON.stringify(u,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let d=n.queryTraces({service:o,symbol:a,since:c,limit:Math.min(l||10,20)});return {handled:true,text:JSON.stringify({count:d.length,traces:d.map(u=>({traceId:u.traceId,services:u.services,spanCount:u.spans.length,totalDurationMs:u.totalDurationMs,startTime:u.startTime,endTime:u.endTime}))},null,2)}}case "paradigm_sentinel_schemas":{let{id:i}=e;if(i){let a=n.getSchema(i);return a?{handled:true,text:JSON.stringify(a,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${i}" not found`})}}let o=n.listSchemas();return o.length===0?{handled:true,text:JSON.stringify({count:0,schemas:[],tip:"No event schemas registered yet. Applications register schemas via POST /api/schemas or SentinelWebClient.registerSchema()."},null,2)}:{handled:true,text:JSON.stringify({count:o.length,schemas:o.map(a=>({id:a.id,version:a.version,name:a.name,description:a.description,eventTypeCount:a.eventTypes.length,scope:a.scope.label,tags:a.tags,registeredAt:a.registeredAt}))},null,2)}}case "paradigm_sentinel_events":{let{schemaId:i,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:u,search:p,limit:g}=e,m=n.queryEvents({schemaId:i,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:u,search:p,limit:Math.min(g||50,100)});return m.length===0?{handled:true,text:JSON.stringify({count:0,events:[],tip:"No events found. Events are ingested via POST /api/events or SentinelWebClient.emit()."},null,2)}:{handled:true,text:JSON.stringify({count:m.length,events:m.map(y=>({id:y.id,schemaId:y.schemaId,eventType:y.eventType,category:y.category,timestamp:y.timestamp,scopeValue:y.scopeValue,service:y.service,severity:y.severity,data:y.data,parentEventId:y.parentEventId,depth:y.depth}))},null,2)}}case "paradigm_sentinel_scopes":{let{schemaId:i,sessionId:o,limit:a}=e,c=n.getEventScopes(i,{limit:Math.min(a||50,200),sessionId:o});return c.length===0?{handled:true,text:JSON.stringify({count:0,scopes:[],tip:`No scopes found for schema "${i}". Events with scope values are required.`},null,2)}:{handled:true,text:JSON.stringify({count:c.length,scopes:c},null,2)}}default:return {handled:false,text:""}}}function Ri(){return [{name:"paradigm_flows_affected",description:"Find flows affected by changes to a symbol. Returns flows that include the symbol in their steps, with downstream impact analysis and validation commands. Returns flow IDs, step positions, and validation commands. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol being modified (e.g., @tasks, ^project-member, !task-created)"},includeValidation:{type:"boolean",description:"Include validation commands in response (default: true)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_flow_check",description:"Check flow definition completeness \u2014 verifies that gates referenced in flows.yaml exist in portal.yaml and that required fields are present. Does not trace code execution paths.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Specific flow ID to validate (e.g., $task-creation). If not provided, validates all flows."},checkImplementation:{type:"boolean",description:"Deep check: verify actions and signals exist in codebase (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ti(t,e,s){switch(t){case "paradigm_flows_affected":{let{symbol:n,includeValidation:r=true}=e,i=await o$3(s.rootDir);if(!i)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:n,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
3
3
  flows:
4
4
  $task-creation:
5
5
  description: "Full task creation flow"
@@ -12,7 +12,7 @@ flows:
12
12
  - id: create
13
13
  action: "Create task record"
14
14
  symbol: "@tasks"
15
- `},null,2)};let o=p$1(i,n),a={symbol:o.symbol,totalFlows:o.totalFlows,impactLevel:o.impactLevel,affectedFlows:o.affectedFlows.map(l=>{let d={flowId:l.flowId,definedIn:l.definedIn,description:l.description,stepAffected:l.stepAffected,downstreamSteps:l.downstreamSteps};return l.trigger&&(d.trigger=l.trigger),r&&l.validation&&(d.validation=l.validation),d}),suggestion:o.suggestion};return r&&o.validationCommands.length>0&&(a.validationCommands=o.validationCommands),{handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_flow_check":case "paradigm_flow_validate":{let{flowId:n,checkImplementation:r=false}=e,i=$.join(s.rootDir,".paradigm","flows.yaml"),o=null;if(A.existsSync(i))try{let h=A.readFileSync(i,"utf-8");o=qe.load(h);}catch(h){return {handled:true,text:JSON.stringify({error:"Failed to parse flows.yaml",details:String(h)},null,2)}}let a={...o?.flows??{}},c=await o$3(s.rootDir);if(c?.flows)for(let[h,b]of Object.entries(c.flows))a[h]||(a[h]={description:b.description,trigger:b.trigger,steps:(b.steps||[]).map(w=>({type:w.symbol?.startsWith("^")?"gate":w.symbol?.startsWith("!")?"signal":"action",symbol:w.symbol??"",description:w.action}))});if(Object.keys(a).length===0)return {handled:true,text:JSON.stringify({error:"No flows found",suggestion:"Create .paradigm/flows.yaml with flow definitions",example:`
15
+ `},null,2)};let o=p$1(i,n),a={symbol:o.symbol,totalFlows:o.totalFlows,impactLevel:o.impactLevel,affectedFlows:o.affectedFlows.map(l=>{let d={flowId:l.flowId,definedIn:l.definedIn,description:l.description,stepAffected:l.stepAffected,downstreamSteps:l.downstreamSteps};return l.trigger&&(d.trigger=l.trigger),r&&l.validation&&(d.validation=l.validation),d}),suggestion:o.suggestion};return r&&o.validationCommands.length>0&&(a.validationCommands=o.validationCommands),{handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_flow_check":case "paradigm_flow_validate":{let{flowId:n,checkImplementation:r=false}=e,i=$.join(s.rootDir,".paradigm","flows.yaml"),o=null;if(I.existsSync(i))try{let h=I.readFileSync(i,"utf-8");o=qe.load(h);}catch(h){return {handled:true,text:JSON.stringify({error:"Failed to parse flows.yaml",details:String(h)},null,2)}}let a={...o?.flows??{}},c=await o$3(s.rootDir);if(c?.flows)for(let[h,b]of Object.entries(c.flows))a[h]||(a[h]={description:b.description,trigger:b.trigger,steps:(b.steps||[]).map(w=>({type:w.symbol?.startsWith("^")?"gate":w.symbol?.startsWith("!")?"signal":"action",symbol:w.symbol??"",description:w.action}))});if(Object.keys(a).length===0)return {handled:true,text:JSON.stringify({error:"No flows found",suggestion:"Create .paradigm/flows.yaml with flow definitions",example:`
16
16
  version: "1.0"
17
17
  flows:
18
18
  $task-creation:
@@ -30,7 +30,7 @@ flows:
30
30
  symbol: "!task-created"
31
31
  description: Emit success event
32
32
  successSignal: "!task-created"
33
- `},null,2)};let l=$.join(s.rootDir,"portal.yaml"),d=[];if(A.existsSync(l))try{let h=A.readFileSync(l,"utf-8"),b=qe.load(h);b?.gates&&(d=Object.keys(b.gates).map(w=>w.startsWith("^")?w.slice(1):w));}catch{}let u=new Set(d),p=[],g=n?[[n,a[n]]]:Object.entries(a);for(let[h,b]of g){if(!b){if(n)return {handled:true,text:JSON.stringify({error:`Flow not found: ${n}`,availableFlows:Object.keys(a)},null,2)};continue}let w={flowId:h,status:"valid",coverage:{gatesReferenced:[],gatesMissing:[],actionsReferenced:[],actionsMissing:[],signalsEmitted:[],signalsMissing:[]},suggestions:[]},x=b.steps||[];for(let k=0;k<x.length;k++){let _=x[k],T=_.symbol||"",C=tc(T);if(C)switch(_.type){case "gate":w.coverage.gatesReferenced.push(T),u.has(C.name)||(w.coverage.gatesMissing.push(T),w.status="invalid");break;case "action":w.coverage.actionsReferenced.push(T);break;case "signal":w.coverage.signalsEmitted.push(T);break}}b.successSignal&&w.coverage.signalsEmitted.push(b.successSignal),w.coverage.gatesMissing.length>0&&w.suggestions.push(`Add missing gates to portal.yaml: ${w.coverage.gatesMissing.join(", ")}`),w.status==="valid"&&w.coverage.gatesMissing.length===0&&(w.status="valid"),p.push(w);}let m=p.filter(h=>h.status==="valid").length,y=p.filter(h=>h.status==="invalid").length,f={status:y>0?"invalid":"valid",totalFlows:p.length,validFlows:m,invalidFlows:y,results:p.map(h=>({flowId:h.flowId,status:h.status,gatesReferenced:h.coverage.gatesReferenced,gatesMissing:h.coverage.gatesMissing,actionsReferenced:h.coverage.actionsReferenced,signalsEmitted:h.coverage.signalsEmitted,suggestions:h.suggestions}))};return {handled:true,text:JSON.stringify(f,null,2)}}default:return {handled:false,text:""}}}function tc(t){let e=t.match(/^([#$^!~])(.+)$/);return e?{prefix:e[1],name:e[2]}:null}b$1();var nc=60*1e3,Ti=new Map;async function Oi(t){let e=$.resolve(t),s=Ti.get(e);if(s&&Date.now()-s.loadedAt<nc)return s.fixtures;let n=await rc(e);return n&&Ti.set(e,{fixtures:n,loadedAt:Date.now()}),n}async function rc(t){let e=$.join(t,".paradigm","fixtures.yaml");if(!A.existsSync(e))return null;try{let s=A.readFileSync(e,"utf8");return qe.load(s)}catch(s){return a.component("#fixtures-loader").error("Error parsing fixtures.yaml",{error:s}),null}}function Nn(t,e){switch(e){case "users":return t.users||{};case "resources":return t.resources||{};case "payloads":return t.payloads||{};case "all":return {users:t.users||{},resources:t.resources||{},payloads:t.payloads||{}};default:return null}}function Ai(t,e,s){return Nn(t,e)?.[s]||null}function En(t){return {users:Object.keys(t.users||{}),resources:Object.keys(t.resources||{}),payloads:Object.keys(t.payloads||{})}}function Ii(){return [{name:"paradigm_test_fixtures",description:"Get test fixtures for validating flows. Returns users (for auth testing), resources (for entity testing), and sample payloads (for API testing). ~150 tokens.",inputSchema:{type:"object",properties:{category:{type:"string",enum:["users","resources","payloads","all"],description:'Category of fixtures to retrieve. Use "all" to get everything.'},name:{type:"string",description:'Specific fixture name within the category (e.g., "admin", "createTask")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Di(t,e,s){switch(t){case "paradigm_test_fixtures":{let{category:n,name:r}=e,i=await Oi(s.rootDir);if(!i)return {handled:true,text:JSON.stringify({error:"Fixtures not found",suggestion:"Create .paradigm/fixtures.yaml with test fixtures. Run `paradigm init` to generate a template.",example:`
33
+ `},null,2)};let l=$.join(s.rootDir,"portal.yaml"),d=[];if(I.existsSync(l))try{let h=I.readFileSync(l,"utf-8"),b=qe.load(h);b?.gates&&(d=Object.keys(b.gates).map(w=>w.startsWith("^")?w.slice(1):w));}catch{}let u=new Set(d),p=[],g=n?[[n,a[n]]]:Object.entries(a);for(let[h,b]of g){if(!b){if(n)return {handled:true,text:JSON.stringify({error:`Flow not found: ${n}`,availableFlows:Object.keys(a)},null,2)};continue}let w={flowId:h,status:"valid",coverage:{gatesReferenced:[],gatesMissing:[],actionsReferenced:[],actionsMissing:[],signalsEmitted:[],signalsMissing:[]},suggestions:[]},x=b.steps||[];for(let k=0;k<x.length;k++){let _=x[k],P=_.symbol||"",C=tc(P);if(C)switch(_.type){case "gate":w.coverage.gatesReferenced.push(P),u.has(C.name)||(w.coverage.gatesMissing.push(P),w.status="invalid");break;case "action":w.coverage.actionsReferenced.push(P);break;case "signal":w.coverage.signalsEmitted.push(P);break}}b.successSignal&&w.coverage.signalsEmitted.push(b.successSignal),w.coverage.gatesMissing.length>0&&w.suggestions.push(`Add missing gates to portal.yaml: ${w.coverage.gatesMissing.join(", ")}`),w.status==="valid"&&w.coverage.gatesMissing.length===0&&(w.status="valid"),p.push(w);}let m=p.filter(h=>h.status==="valid").length,y=p.filter(h=>h.status==="invalid").length,f={status:y>0?"invalid":"valid",totalFlows:p.length,validFlows:m,invalidFlows:y,results:p.map(h=>({flowId:h.flowId,status:h.status,gatesReferenced:h.coverage.gatesReferenced,gatesMissing:h.coverage.gatesMissing,actionsReferenced:h.coverage.actionsReferenced,signalsEmitted:h.coverage.signalsEmitted,suggestions:h.suggestions}))};return {handled:true,text:JSON.stringify(f,null,2)}}default:return {handled:false,text:""}}}function tc(t){let e=t.match(/^([#$^!~])(.+)$/);return e?{prefix:e[1],name:e[2]}:null}b$1();var nc=60*1e3,Pi=new Map;async function Oi(t){let e=$.resolve(t),s=Pi.get(e);if(s&&Date.now()-s.loadedAt<nc)return s.fixtures;let n=await rc(e);return n&&Pi.set(e,{fixtures:n,loadedAt:Date.now()}),n}async function rc(t){let e=$.join(t,".paradigm","fixtures.yaml");if(!I.existsSync(e))return null;try{let s=I.readFileSync(e,"utf8");return qe.load(s)}catch(s){return a.component("#fixtures-loader").error("Error parsing fixtures.yaml",{error:s}),null}}function Nn(t,e){switch(e){case "users":return t.users||{};case "resources":return t.resources||{};case "payloads":return t.payloads||{};case "all":return {users:t.users||{},resources:t.resources||{},payloads:t.payloads||{}};default:return null}}function Ai(t,e,s){return Nn(t,e)?.[s]||null}function En(t){return {users:Object.keys(t.users||{}),resources:Object.keys(t.resources||{}),payloads:Object.keys(t.payloads||{})}}function Ii(){return [{name:"paradigm_test_fixtures",description:"Get test fixtures for validating flows. Returns users (for auth testing), resources (for entity testing), and sample payloads (for API testing). ~150 tokens.",inputSchema:{type:"object",properties:{category:{type:"string",enum:["users","resources","payloads","all"],description:'Category of fixtures to retrieve. Use "all" to get everything.'},name:{type:"string",description:'Specific fixture name within the category (e.g., "admin", "createTask")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Di(t,e,s){switch(t){case "paradigm_test_fixtures":{let{category:n,name:r}=e,i=await Oi(s.rootDir);if(!i)return {handled:true,text:JSON.stringify({error:"Fixtures not found",suggestion:"Create .paradigm/fixtures.yaml with test fixtures. Run `paradigm init` to generate a template.",example:`
34
34
  version: "1.0"
35
35
 
36
36
  users:
@@ -56,17 +56,17 @@ payloads:
56
56
  createTask:
57
57
  title: "New Task"
58
58
  description: "Task description"
59
- `},null,2)};if(!n){let c=En(i);return {handled:true,text:JSON.stringify({available:c,usage:{getAllUsers:'paradigm_test_fixtures({ category: "users" })',getSpecificUser:'paradigm_test_fixtures({ category: "users", name: "admin" })',getAllPayloads:'paradigm_test_fixtures({ category: "payloads" })',getEverything:'paradigm_test_fixtures({ category: "all" })'}},null,2)}}if(r&&n!=="all"){let c=Ai(i,n,r);if(!c){let d=En(i);return {handled:true,text:JSON.stringify({error:`Fixture "${r}" not found in category "${n}"`,availableInCategory:d[n]||[]},null,2)}}return {handled:true,text:JSON.stringify(c,null,2)}}let o=Nn(i,n);return {handled:true,text:JSON.stringify(o,null,2)}}default:return {handled:false,text:""}}}function $i(t){let e=$.join(t,".paradigm","tags.yaml");if(!A.existsSync(e))return null;try{let s=A.readFileSync(e,"utf-8");return qe.load(s)}catch{return null}}function sc(t,e){let s=$.join(t,".paradigm","tags.yaml"),n=qe.dump(e,{lineWidth:-1});A.writeFileSync(s,n,"utf-8");}function Hi(){return [{name:"paradigm_tags",description:"List, search, and manage tags in the Tag Bank. Use to find available tags for classification. Returns tags organized by section (core, project, suggested) with usage counts. ~150 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","search","get"],description:"Action: list all tags, search by query, or get specific tag details"},query:{type:"string",description:"For search action: query string to match tag names and descriptions"},tag:{type:"string",description:"For get action: specific tag name to get details for"},category:{type:"string",enum:["core","project","suggested","all"],description:"Filter by tag category (default: all)"}},required:["action"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_tags_suggest",description:"AI proposes a new tag for human review. Tag will be added to the suggested section for approval. Returns confirmation of suggestion with section placement. ~100 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:'Tag name (kebab-case, e.g., "webhook-handler")'},description:{type:"string",description:"What this tag means and when to apply it"},reason:{type:"string",description:'Why this tag would be useful (e.g., "Found 5 components handling webhooks")'},appliesTo:{type:"array",items:{type:"string"},description:'Symbol types this tag applies to (e.g., ["#", "$"])'},exampleSymbols:{type:"array",items:{type:"string"},description:"Example symbols that would use this tag"}},required:["tag","description","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_check",description:"Verify an aspect has valid anchors and check coverage. Aspects (~) REQUIRE code anchors. Returns anchor validity, coverage stats, and missing anchor warnings. ~150 tokens.",inputSchema:{type:"object",properties:{aspect:{type:"string",description:'Aspect symbol to check (e.g., "~audit-required")'}},required:["aspect"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["cross-cutting","aspect enforcement","policy check","verify aspect"]}]}async function Fi(t,e,s){switch(t){case "paradigm_tags":{let{action:n,query:r,tag:i,category:o="all"}=e,a=$i(s.rootDir);if(!a)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml or run `paradigm init` to set up tags"})};if(n==="list"){let c={};return (o==="all"||o==="core")&&(c.core=Object.entries(a.core).map(([l,d])=>({tag:l,description:d.description?.split(`
59
+ `},null,2)};if(!n){let c=En(i);return {handled:true,text:JSON.stringify({available:c,usage:{getAllUsers:'paradigm_test_fixtures({ category: "users" })',getSpecificUser:'paradigm_test_fixtures({ category: "users", name: "admin" })',getAllPayloads:'paradigm_test_fixtures({ category: "payloads" })',getEverything:'paradigm_test_fixtures({ category: "all" })'}},null,2)}}if(r&&n!=="all"){let c=Ai(i,n,r);if(!c){let d=En(i);return {handled:true,text:JSON.stringify({error:`Fixture "${r}" not found in category "${n}"`,availableInCategory:d[n]||[]},null,2)}}return {handled:true,text:JSON.stringify(c,null,2)}}let o=Nn(i,n);return {handled:true,text:JSON.stringify(o,null,2)}}default:return {handled:false,text:""}}}function $i(t){let e=$.join(t,".paradigm","tags.yaml");if(!I.existsSync(e))return null;try{let s=I.readFileSync(e,"utf-8");return qe.load(s)}catch{return null}}function sc(t,e){let s=$.join(t,".paradigm","tags.yaml"),n=qe.dump(e,{lineWidth:-1});I.writeFileSync(s,n,"utf-8");}function Hi(){return [{name:"paradigm_tags",description:"List, search, and manage tags in the Tag Bank. Use to find available tags for classification. Returns tags organized by section (core, project, suggested) with usage counts. ~150 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","search","get"],description:"Action: list all tags, search by query, or get specific tag details"},query:{type:"string",description:"For search action: query string to match tag names and descriptions"},tag:{type:"string",description:"For get action: specific tag name to get details for"},category:{type:"string",enum:["core","project","suggested","all"],description:"Filter by tag category (default: all)"}},required:["action"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_tags_suggest",description:"AI proposes a new tag for human review. Tag will be added to the suggested section for approval. Returns confirmation of suggestion with section placement. ~100 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:'Tag name (kebab-case, e.g., "webhook-handler")'},description:{type:"string",description:"What this tag means and when to apply it"},reason:{type:"string",description:'Why this tag would be useful (e.g., "Found 5 components handling webhooks")'},appliesTo:{type:"array",items:{type:"string"},description:'Symbol types this tag applies to (e.g., ["#", "$"])'},exampleSymbols:{type:"array",items:{type:"string"},description:"Example symbols that would use this tag"}},required:["tag","description","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_check",description:"Verify an aspect has valid anchors and check coverage. Aspects (~) REQUIRE code anchors. Returns anchor validity, coverage stats, and missing anchor warnings. ~150 tokens.",inputSchema:{type:"object",properties:{aspect:{type:"string",description:'Aspect symbol to check (e.g., "~audit-required")'}},required:["aspect"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["cross-cutting","aspect enforcement","policy check","verify aspect"]}]}async function Fi(t,e,s){switch(t){case "paradigm_tags":{let{action:n,query:r,tag:i,category:o="all"}=e,a=$i(s.rootDir);if(!a)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml or run `paradigm init` to set up tags"})};if(n==="list"){let c={};return (o==="all"||o==="core")&&(c.core=Object.entries(a.core).map(([l,d])=>({tag:l,description:d.description?.split(`
60
60
  `)[0].trim(),color:d.color,appliesTo:d["applies-to"]}))),(o==="all"||o==="project")&&(c.project=Object.entries(a.project||{}).map(([l,d])=>({tag:l,description:d.description?.split(`
61
61
  `)[0].trim(),color:d.color,appliesTo:d["applies-to"]}))),(o==="all"||o==="suggested")&&(c.suggested=(a.suggested||[]).map(l=>({tag:l.tag,reason:l.reason,proposedBy:l["proposed-by"],proposedAt:l["proposed-at"]}))),c.summary={coreCount:Object.keys(a.core||{}).length,projectCount:Object.keys(a.project||{}).length,suggestedCount:(a.suggested||[]).length},{handled:true,text:JSON.stringify(c,null,2)}}if(n==="search"){if(!r)return {handled:true,text:JSON.stringify({error:"Query required for search action"})};let c=r.toLowerCase(),l=[];for(let[d,u]of Object.entries(a.core||{}))(d.toLowerCase().includes(c)||u.description?.toLowerCase().includes(c)||u.aliases?.some(p=>p.toLowerCase().includes(c)))&&l.push({tag:d,category:"core",description:u.description?.split(`
62
62
  `)[0].trim()||""});for(let[d,u]of Object.entries(a.project||{}))(d.toLowerCase().includes(c)||u.description?.toLowerCase().includes(c)||u.aliases?.some(p=>p.toLowerCase().includes(c)))&&l.push({tag:d,category:"project",description:u.description?.split(`
63
- `)[0].trim()||""});return {handled:true,text:JSON.stringify({query:r,count:l.length,matches:l},null,2)}}if(n==="get"){if(!i)return {handled:true,text:JSON.stringify({error:"Tag name required for get action"})};if(a.core?.[i]){let l=a.core[i];return {handled:true,text:JSON.stringify({tag:i,category:"core",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}if(a.project?.[i]){let l=a.project[i];return {handled:true,text:JSON.stringify({tag:i,category:"project",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}let c=a.suggested?.find(l=>l.tag===i);return c?{handled:true,text:JSON.stringify({tag:i,category:"suggested",reason:c.reason,proposedBy:c["proposed-by"],proposedAt:c["proposed-at"],appliesTo:c["applies-to"],exampleSymbols:c["example-symbols"],status:"pending approval"},null,2)}:{handled:true,text:JSON.stringify({error:`Tag "${i}" not found`,suggestion:'Use paradigm_tags with action "list" to see available tags'})}}return {handled:true,text:JSON.stringify({error:`Unknown action: ${n}`})}}case "paradigm_tags_suggest":{let{tag:n,description:r,reason:i,appliesTo:o,exampleSymbols:a}=e,c=$i(s.rootDir);if(!c)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml first"})};if(c.core?.[n]||c.project?.[n])return {handled:true,text:JSON.stringify({error:`Tag "${n}" already exists`,existing:c.core?.[n]?"core":"project"})};if(c.suggested?.some(d=>d.tag===n))return {handled:true,text:JSON.stringify({error:`Tag "${n}" is already in the suggested queue`,status:"pending approval"})};let l={tag:n,"proposed-by":"claude","proposed-at":new Date().toISOString(),reason:i,"applies-to":o||["#"],"example-symbols":a};return c.suggested||(c.suggested=[]),c.suggested.push(l),sc(s.rootDir,c),{handled:true,text:JSON.stringify({success:true,tag:n,status:"pending approval",message:"Tag suggestion added. Human review required before use.",nextSteps:["Human can approve via Sentinel UI or CLI",'Once approved, tag moves to "project" section',"Then AI can use the tag for classification"]},null,2)}}case "paradigm_aspect_check":{let{aspect:n}=e,r=n.startsWith("~")?n:`~${n}`,i=k(s.index,r);if(!i)return {handled:true,text:JSON.stringify({error:`Aspect "${r}" not found`,suggestion:"Use paradigm_search to find available aspects"})};if(i.type!=="aspect")return {handled:true,text:JSON.stringify({error:`Symbol "${r}" is not an aspect (type: ${i.type})`,note:"Only ~ symbols are aspects"})};let o=i.anchors||[],a=i.filePath?$.isAbsolute(i.filePath)?i.filePath:$.resolve(s.rootDir,i.filePath):s.rootDir,c=i.filePath?$.dirname(a):s.rootDir,l=[];for(let f of o){let v=r$1(f.path,c,s.rootDir),h=v.resolvedPath,b=v.exists,w;if(b)try{let _=A.readFileSync(h,"utf-8").split(`
64
- `);typeof f.lines=="number"?w=1:Array.isArray(f.lines)&&f.lines.length===2?w=f.lines[1]-f.lines[0]+1:Array.isArray(f.lines)&&(w=f.lines.length);}catch{}let x;b||s$1(f.path,c,s.rootDir).mismatch&&(x="Anchor resolves under .purpose-dir base but not project-root base (or vice versa). This indicates a framework path-resolution bug; do NOT hand-edit. Run `paradigm_aspect_drift` for full audit, or file framework-bug task per protocol."),l.push({path:f.path,lines:f.raw.split(":")[1]||"full file",exists:b,lineCount:w,...x?{resolution_hint:x}:{}});}let d=o.length>0&&l.every(f=>f.exists),u=i.appliesTo||[],p=q(s.index),g=[],m=[];for(let f of p)for(let v of u)if(new RegExp("^"+v.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(f.symbol)){g.push(f.symbol),(f.data?.aspects?.includes?.(r)||f.data?.aspects?.includes?.(n))&&m.push(f.symbol);break}let y=g.filter(f=>!m.includes(f));return {handled:true,text:JSON.stringify({aspect:r,valid:d,description:i.description,enforcement:i.enforcement,anchors:l,coverage:{appliesTo:u,matchingSymbols:g.length,symbolsWithAspect:m.length,missing:y.slice(0,10),missingCount:y.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...l.filter(f=>!f.exists).map(f=>`Anchor file not found: ${f.path}`),...y.length>0?[`${y.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:d?y.length>0?"Aspect is valid but has coverage gaps - consider applying to matching symbols":"Aspect is valid and fully applied":"INVALID: Add code anchors to this aspect"},null,2)}}default:return {handled:false,text:""}}}b$1();var re=class extends Error{code="WRITE_VERIFICATION_FAILED";constructor(e="write verification failed"){super(e),this.name="WriteVerificationError";}},ic=".paradigm-install-key",oc="paradigm-v5.38.0-hmac-fallback-key",ve=null;function ac(){if(ve)return ve;try{let t=Ni.homedir(),e=$.join(t,ic);if(A.existsSync(e)){let n=A.readFileSync(e,"utf-8").trim();if(/^[0-9a-f]{64}$/i.test(n))return ve=Buffer.from(n,"hex"),ve}let s=ct.randomBytes(32);try{A.writeFileSync(e,s.toString("hex"),{encoding:"utf-8",mode:384});}catch{}return ve=s,ve}catch{return ve=Buffer.from(oc),ve}}function cc(t){let e=ct.createHmac("sha256",ac());return e.update(t),e.digest("hex").slice(0,12)}function lc(t,e){let s=$.dirname(t),n=`.${$.basename(t)}.${process.pid}.${Date.now()}.${ct.randomBytes(4).toString("hex")}.tmp`,r=$.join(s,n);try{A.writeFileSync(r,e,{encoding:"utf-8"}),A.renameSync(r,t);}catch(i){try{A.unlinkSync(r);}catch{}throw i}}async function lt(t,e,s){lc(t,e);let n;try{n=A.readFileSync(t,"utf-8");}catch{throw a.component("#write-and-confirm").error("read-back failed after atomic write",{stage:"read-back"}),new re("write verification failed (read-back error)")}let r=false;try{r=s(n);}catch{throw a.component("#write-and-confirm").error("verify callback threw",{stage:"verify-callback",strict:b$d()}),new re("write verification failed (verify callback error)")}if(!r)throw a.component("#write-and-confirm").error("verify callback returned false",{stage:"verify-callback-false",strict:b$d()}),new re("write verification failed");let i=Buffer.byteLength(n,"utf-8"),o=cc(n);return {written:true,path:t,hashHint:o,bytes:i}}b$1();var dc=["#","$","^","!","~"];function H(t){return t.length>1&&dc.includes(t[0])?t.slice(1):t}function F(t,e){let s=H(t);return `${e}${s}`}function ee(t,e){let s=$.isAbsolute(t)?t:$.resolve(e,t);return s.endsWith(".purpose")?s:$.join(s,".purpose")}function M(t){if(!A.existsSync(t))return {};let e=b$c(t);if(!e.data)throw new Error(`Failed to parse ${t}: ${e.errors.join(", ")}`);return e.data}function we(t,e){let s=$.dirname(t);A.existsSync(s)||A.mkdirSync(s,{recursive:true});let n=c$7(e);A.writeFileSync(t,n,"utf8");}async function Ft(t,e,s,n="purpose.yaml"){let r=$.dirname(t);A.existsSync(r)||A.mkdirSync(r,{recursive:true});let i=c$7(e);try{return await lt(t,i,o=>{let a=b$c(t);if(!a.data)return !1;try{return s(a.data)}catch{return !1}})}catch(o){throw o instanceof re?(a.component("#purpose-writer").error("purpose write verification failed",{surface:n,stage:"writeAndConfirm"}),new Error(`purpose write verification failed (${n})`)):o}}function Pe(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t){let{id:n,...r}=s;e[n]=r;}return e}function Ne(t){if(!t)return {};if(!Array.isArray(t)){let s={};for(let[n,r]of Object.entries(t))!n||n==="undefined"||(s[n]=r);return s}let e={};for(let s of t)!s||!s.name||(e[s.name]={description:s.description,steps:s.steps});return e}function Ee(t,e){if(!e||e.length===0)return t;if(!t||t.length===0)return e;let s=new Set(t);for(let n of e)s.add(n);return Array.from(s)}var pc={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function Ei(t,e,s,n){let r=pc[n];if(!r)throw new Error(`Invalid symbol type: ${n}. Expected one of: # ^ ! $ ~`);let i=H(e),o=H(s),a=F(i,r),c=F(o,r),l=await d$8(t),d=[];for(let u of l){let p=M(u),g=false,y={"#":"components","^":"gates","!":"signals",$:"flows","~":"aspects"}[r];if(y&&y!=="flows"){let f=p[y];f&&!Array.isArray(f)&&i in f&&(f[o]=f[i],delete f[i],g=true);}if(r==="#")for(let f of ["features","components"]){let v=p[f];v&&!Array.isArray(v)&&i in v&&(v[o]=v[i],delete v[i],g=true);}r==="$"&&p.flows&&!Array.isArray(p.flows)&&i in p.flows&&(p.flows[o]=p.flows[i],delete p.flows[i],g=true);for(let f of ["features","components"]){let v=Pe(p[f]);for(let[h,b]of Object.entries(v))g=uc(b,a,c)||g;g&&Object.keys(v).length>0&&(p[f]=v);}if(p.flows){let f=Ne(p.flows);for(let[v,h]of Object.entries(f)){if(h.gates){let b=h.gates.indexOf(a);b!==-1&&(h.gates[b]=c,g=true);}if(h.signals){let b=h.signals.indexOf(a);b!==-1&&(h.signals[b]=c,g=true);}if(h.components){let b=h.components.indexOf(a);b!==-1&&(h.components[b]=c,g=true);}if(h.steps)for(let b of h.steps)typeof b=="object"&&"component"in b&&(b.component===a||b.component===i)&&(b.component=r==="#"?o:c,g=true);}g&&(p.flows=f);}if(p.gates){for(let[f,v]of Object.entries(p.gates))if(v.signals){let h=v.signals.indexOf(a);h!==-1&&(v.signals[h]=c,g=true);}}if(p.aspects){for(let[f,v]of Object.entries(p.aspects))if(v["applies-to"]){let h=v["applies-to"].indexOf(a);h!==-1&&(v["applies-to"][h]=c,g=true);}}g&&(we(u,p),d.push(u));}return d}function uc(t,e,s){let n=false,r=["signals","gates","flows","components","states"];for(let i of r){let o=t[i];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,n=true);}}if(t.aspects&&Array.isArray(t.aspects)){let i=t.aspects.indexOf(e);i!==-1&&(t.aspects[i]=s,n=true);}return n}b$1();function gc(t){return h$6(t)}function Et(t,e){if(!A.existsSync(t))return {status:"missing"};let s;try{s=A.readFileSync(t,"utf-8");}catch{return qn({status:"unparseable",errorClass:"other",detail:"file read error"})}let n;try{n=qe.load(s);}catch(r){let{errorClass:i,detail:o}=gc(r);return qn({status:"unparseable",errorClass:i,detail:o})}return {status:"ok",data:n}}function qn(t,e){if(!(b$d())||t.status==="ok"||t.status==="missing")return t;throw new Error(`yaml load failed under PARADIGM_STRICT=1 (${t.errorClass}: ${t.detail})`)}function qt(t){let e=$.join(t,"portal.yaml"),s=Et(e);if(s.status==="missing")return {data:{version:"1.0.0",gates:{}},filePath:e};if(s.status==="unparseable"||s.status==="invalid")throw a.component("#portal-writer").error("portal.yaml unparseable on read",{errorClass:s.errorClass}),new Error(`portal.yaml unparseable (${s.errorClass}). Refusing to overwrite. Run 'paradigm doctor' for line-specific details.`);return {data:s.data||{version:"1.0.0",gates:{}},filePath:e}}async function Mi(t,e){let{data:s,filePath:n}=qt(t);if(!s.gates||Array.isArray(s.gates)){let a=s.gates;if(s.gates={},Array.isArray(a)&&a.length>0){for(let c of a)if(c&&typeof c=="object"&&"id"in c){let l=H(c.id);s.gates[l]=c;}}}let r=H(e.id),i=s.gates[r]||{};i.description=e.description,e.type!==void 0&&(i.type=e.type),e.location!==void 0&&(i.location=e.location),e.requires!==void 0&&(i.requires=e.requires),e.check!==void 0&&(i.check=e.check),e.grants!==void 0&&(i.grants=e.grants),e.emits!==void 0&&(i.emits=e.emits),e.prizes!==void 0&&(i.prizes=e.prizes),i.prizes||(i.prizes=[]),s.gates[r]=i;let o=qe.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await lt(n,o,a=>{let c;try{c=qe.load(a);}catch{return !1}let l=c?.gates;return !l||Array.isArray(l)?!1:!!l[r]})}catch(a$1){throw a$1 instanceof re?(a.component("#portal-writer").error("portal_add_gate write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_gate write verification failed")):a$1}}async function Gi(t,e){let{data:s,filePath:n}=qt(t);(!s.routes||Array.isArray(s.routes))&&(s.routes={});let r=`${e.method} ${e.route}`,i=e.gates.map(a=>`^${H(a)}`);s.routes[r]=i;let o=qe.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await lt(n,o,a=>{let c;try{c=qe.load(a);}catch{return !1}let l=c?.routes;return !l||Array.isArray(l)?!1:!!l[r]})}catch(a$1){throw a$1 instanceof re?(a.component("#portal-writer").error("portal_add_route write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_route write verification failed")):a$1}}var fc={name:"paradigm_purpose_init",description:"Create or update file-level metadata on a .purpose file. Does NOT overwrite existing components/signals/etc \u2014 only touches top-level metadata (name, description, context, version). ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory (relative to project root)"},name:{type:"string",description:"Name/title for this purpose file"},description:{type:"string",description:"Description of what this directory/module does"},context:{type:"array",items:{type:"string"},description:"Context notes for AI agents"},version:{type:"string",description:'Version string (default: "1.0.0")'}},required:["purposeFile","name"]},annotations:{readOnlyHint:false,destructiveHint:false}},mc={name:"paradigm_purpose_add_component",description:"Add or update a component (#) or feature in a .purpose file. Strips # prefix from id automatically. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Component ID (e.g. "payment-service" or "#payment-service")'},description:{type:"string",description:"What this component does"},section:{type:"string",enum:["components","features"],description:'Which section to add to (default: "components")'},file:{type:"string",description:"Source file path for this component"},status:{type:"string",description:'Component status (e.g. "active", "deprecated")'},endpoints:{type:"array",items:{type:"string"},description:'API endpoints (e.g. ["POST /api/payments"])'},tests:{type:"array",items:{type:"string"},description:"Test file paths"},flows:{type:"array",items:{type:"string"},description:'Flow references (e.g. ["$checkout-flow"])'},gates:{type:"array",items:{type:"string"},description:'Gate references (e.g. ["^authenticated"])'},signals:{type:"array",items:{type:"string"},description:'Signal references (e.g. ["!payment-completed"])'},aspects:{type:"array",items:{type:"string"},description:'Aspect references (e.g. ["~audit-required"])'},components:{type:"array",items:{type:"string"},description:'Component references (e.g. ["#stripe-service"])'},type:{type:"string",description:'Component type (e.g., "view", "service", "model", "tool"). Open string per project vocabulary.'},parent:{type:"string",description:'Parent component (e.g., "#payment-page"). Establishes hierarchy.'}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},yc={name:"paradigm_purpose_add_aspect",description:'Add or update an aspect (~) with ENFORCED anchors. Anchors are required and must point to code locations. Strips ~ prefix automatically. This prevents the common "~aspect:name" format error. ~100 tokens.',inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Aspect ID (e.g. "audit-required" or "~audit-required")'},description:{type:"string",description:"What this aspect enforces"},anchors:{type:"array",items:{type:"string"},description:'REQUIRED. Code anchor locations (e.g. ["src/middleware/audit.ts:15-35"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g. ["compliance", "security"])'},appliesTo:{type:"array",items:{type:"string"},description:'Glob patterns for symbols this applies to (e.g. ["#*Service"])'},enforcement:{type:"string",description:'How this aspect is enforced (e.g. "middleware", "decorator")'}},required:["purposeFile","id","description","anchors"]},annotations:{readOnlyHint:false,destructiveHint:false}},hc={name:"paradigm_purpose_add_signal",description:"Add a signal (!) definition. Handles YAML ! quoting automatically. Strips ! prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Signal ID (e.g. "payment-completed" or "!payment-completed")'},description:{type:"string",description:"What this signal represents"},category:{type:"string",description:'Signal category (e.g. "business", "system", "security")'},severity:{type:"string",enum:["info","warn","error"],description:"Severity level"},emitters:{type:"array",items:{type:"string"},description:'Components that emit this signal (e.g. ["#payment-service"])'},related:{type:"array",items:{type:"string"},description:"Related signals or symbols"},data:{type:"object",description:"Schema/shape of data emitted with this signal"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},bc={name:"paradigm_purpose_add_flow",description:"Add a flow ($) definition. Strips $ prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Flow ID (e.g. "checkout-flow" or "$checkout-flow")'},description:{type:"string",description:"What this flow does"},gates:{type:"array",items:{type:"string"},description:"Gate references in this flow"},signals:{type:"array",items:{type:"string"},description:"Signals emitted during this flow"},components:{type:"array",items:{type:"string"},description:"Components involved in this flow"},steps:{type:"array",items:{type:"object",properties:{component:{type:"string"},action:{type:"string"},description:{type:"string"}},required:["component","action"]},description:"Ordered steps in the flow"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},vc={name:"paradigm_purpose_add_gate",description:"Add a gate (^) to a .purpose file's gates section. This is for purpose-level gates, NOT portal.yaml. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},requires:{type:"array",items:{type:"string"},description:"Requirements for this gate"},keys:{type:"array",items:{type:"string"},description:"Key expressions for gate evaluation"},signals:{type:"array",items:{type:"string"},description:"Signals emitted by this gate (e.g. on pass/fail)"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},wc={name:"paradigm_purpose_add_state",description:"Add a state definition to a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'State ID (e.g. "user-store")'},description:{type:"string",description:"What this state represents"},type:{type:"string",description:'Type of state (e.g. "object", "array", "string")'},default:{description:"Default value for the state"},properties:{type:"object",description:"State properties as {name: {type, description}}"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},kc={name:"paradigm_purpose_link",description:"Add references to an existing component without rewriting all fields. Merges into existing arrays (no clobber). Example: add ~rate-limited to #payment-service's aspects. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},componentId:{type:"string",description:"Component or feature ID to add references to"},section:{type:"string",enum:["components","features"],description:"Which section the component is in (default: auto-detect)"},signals:{type:"array",items:{type:"string"},description:"Signal references to add"},aspects:{type:"array",items:{type:"string"},description:"Aspect references to add"},gates:{type:"array",items:{type:"string"},description:"Gate references to add"},flows:{type:"array",items:{type:"string"},description:"Flow references to add"},components:{type:"array",items:{type:"string"},description:"Component references to add"}},required:["purposeFile","componentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},_c={name:"paradigm_purpose_remove",description:"Remove any element by section + id from a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},section:{type:"string",enum:["components","features","gates","signals","aspects","flows","states"],description:"Which section to remove from"},id:{type:"string",description:"ID of the element to remove"}},required:["purposeFile","section","id"]},annotations:{readOnlyHint:false,destructiveHint:true}},Sc={name:"paradigm_purpose_rename",description:"Rename a symbol across ALL .purpose files in the project. Updates both definitions and references. ~200 tokens.",inputSchema:{type:"object",properties:{oldId:{type:"string",description:'Current symbol ID (e.g. "payment-service")'},newId:{type:"string",description:'New symbol ID (e.g. "billing-service")'},symbolType:{type:"string",enum:["#","^","!","$","~"],description:"Symbol type prefix"}},required:["oldId","newId","symbolType"]},annotations:{readOnlyHint:false,destructiveHint:false}},xc={name:"paradigm_portal_add_gate",description:"Add or update a gate (^) in portal.yaml. Creates portal.yaml if it doesn't exist. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},type:{type:"string",description:'Gate type (e.g. "auth", "role", "ownership")'},location:{type:"string",description:'Where the gate is checked in your code (e.g. "middleware", "route-handler")'},requires:{type:"array",items:{type:"string"},description:"Prerequisite gates"},check:{type:"string",description:'Expression to evaluate (e.g. "req.user != null")'},grants:{type:"array",items:{type:"string"},description:"What passing this gate grants access to"},emits:{type:"array",items:{type:"string"},description:"Signals emitted when gate is checked"},prizes:{type:"array",items:{type:"object",properties:{id:{type:"string"},oneTime:{type:"boolean"}},required:["id"]},description:"Side effects triggered on pass"}},required:["id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Cc={name:"paradigm_portal_add_route",description:"Add a route with gates to portal.yaml. Creates routes section if needed. ~100 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:'Route path (e.g. "/api/users/:id")'},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},gates:{type:"array",items:{type:"string"},description:'Gate IDs to apply (e.g. ["^authenticated", "^user-owner"])'}},required:["route","method","gates"]},annotations:{readOnlyHint:false,destructiveHint:false}},Rc={name:"paradigm_purpose_validate",description:"Validate .purpose files and portal.yaml. Returns issues found. If no purposeFile specified, validates all files. ~200 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Specific .purpose file to validate (validates all if omitted)"},includePortal:{type:"boolean",description:"Also validate portal.yaml (default: true)"}}},annotations:{readOnlyHint:true,destructiveHint:false}};function Ui(){return [fc,mc,yc,hc,bc,vc,wc,kc,_c,Sc,xc,Cc,Rc]}async function Wi(t,e,s,n){switch(t){case "paradigm_purpose_init":return Pc(e,s,n);case "paradigm_purpose_add_component":return Tc(e,s,n);case "paradigm_purpose_add_aspect":return jc(e,s,n);case "paradigm_purpose_add_signal":return Oc(e,s,n);case "paradigm_purpose_add_flow":return Ac(e,s,n);case "paradigm_purpose_add_gate":return Ic(e,s,n);case "paradigm_purpose_add_state":return Dc(e,s,n);case "paradigm_purpose_link":return $c(e,s,n);case "paradigm_purpose_remove":return Hc(e,s,n);case "paradigm_purpose_rename":return Fc(e,s,n);case "paradigm_portal_add_gate":return Nc(e,s,n);case "paradigm_portal_add_route":return Ec(e,s,n);case "paradigm_purpose_validate":return Lc(e,s);default:return {handled:false,text:""}}}function z(t){return {handled:true,text:JSON.stringify(t,null,2)}}function W(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}async function Pc(t,e,s){let{purposeFile:n,name:r,description:i,context:o,version:a}=t,c=ee(n,e.rootDir),l=M(c);return a!==void 0?l.version=a:l.version||(l.version="1.0.0"),i!==void 0?l.description=i:l.description||(l.description=r),o!==void 0&&(l.context=o),we(c,l),await s(),z({action:"purpose_init",file:c,metadata:{name:r,description:l.description,version:l.version}})}async function Tc(t,e,s){let{purposeFile:n,id:r,description:i,section:o="components",file:a,status:c,endpoints:l,tests:d,flows:u,gates:p,signals:g,aspects:m,components:y,type:f,parent:v}=t,h=ee(n,e.rootDir),b=M(h),w=H(r),x=o,k=Pe(b[x]),_=k[w]||{description:""};_.description=i,a!==void 0&&(_.file=a),c!==void 0&&(_.status=c),l!==void 0&&(_.endpoints=l),d!==void 0&&(_.tests=d),u!==void 0&&(_.flows=u.map(C=>F(C,"$"))),p!==void 0&&(_.gates=p.map(C=>F(C,"^"))),g!==void 0&&(_.signals=g.map(C=>F(C,"!"))),m!==void 0&&(_.aspects=m.map(C=>F(C,"~"))),y!==void 0&&(_.components=y.map(C=>F(C,"#"))),f!==void 0&&(_.type=f),v!==void 0&&(_.parent=F(v,"#")),k[w]=_,b[x]=k;let T=await Ft(h,b,C=>{let j=C[x];return !j||typeof j!="object"||Array.isArray(j)?!1:w in j},x);return await s(),z({action:"add_component",file:T.path,section:x,id:w,symbol:`#${w}`,written:T.written,hashHint:T.hashHint,bytes:T.bytes})}async function jc(t,e,s){let{purposeFile:n,id:r,description:i,anchors:o,tags:a,appliesTo:c,enforcement:l}=t;if(!o||o.length===0)return W('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let f of o)if(!d.test(f))return W(`Invalid anchor format: "${f}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let u=ee(n,e.rootDir),p=$.dirname(u);for(let f of o){let v=f.replace(/:.*$/,""),h=$.resolve(p,v);if(!A.existsSync(h)){let b=$.resolve(e.rootDir,v);if(A.existsSync(b)){let w=$.relative(p,b),x=o.indexOf(f);o[x]=f.replace(v,w);}else return W(`Anchor file not found: "${v}". Anchors must be relative to the .purpose file directory (${p}).`)}}let g=M(u);(!g.aspects||Array.isArray(g.aspects))&&(g.aspects={});let m=H(r);g.aspects[m]={description:i,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},we(u,g);let y=M(u).aspects;return !y||Array.isArray(y)||!y[m]?W(`add_aspect write verification failed: aspect "${m}" not found in ${u} after write.`):(await s(),z({action:"add_aspect",file:u,id:m,symbol:`~${m}`,anchors:o}))}async function Oc(t,e,s){let{purposeFile:n,id:r,description:i,category:o,severity:a,emitters:c,related:l,data:d}=t,u=ee(n,e.rootDir),p=M(u);(!p.signals||Array.isArray(p.signals))&&(p.signals={});let g=H(r);p.signals[g]={description:i,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(y=>F(y,"#"))},...l&&{related:l},...d&&{data:d}},we(u,p);let m=M(u).signals;return !m||Array.isArray(m)||!m[g]?W(`add_signal write verification failed: signal "${g}" not found in ${u} after write.`):(await s(),z({action:"add_signal",file:u,id:g,symbol:`!${g}`}))}async function Ac(t,e,s){let{purposeFile:n,id:r,description:i,gates:o,signals:a,components:c,steps:l}=t,d=ee(n,e.rootDir),u=M(d),p=Ne(u.flows),g=H(r),m={description:i,...o&&{gates:o.map(f=>F(f,"^"))},...a&&{signals:a.map(f=>F(f,"!"))},...c&&{components:c.map(f=>F(f,"#"))},...l&&{steps:l}};return p[g]=m,u.flows=p,we(d,u),Ne(M(d).flows)[g]?(await s(),z({action:"add_flow",file:d,id:g,symbol:`$${g}`})):W(`add_flow write verification failed: flow "${g}" not found in ${d} after write.`)}async function Ic(t,e,s){let{purposeFile:n,id:r,description:i,requires:o,keys:a,signals:c}=t,l=ee(n,e.rootDir),d=M(l);(!d.gates||Array.isArray(d.gates))&&(d.gates={});let u=H(r);d.gates[u]={description:i,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(g=>F(g,"!"))}},we(l,d);let p=M(l).gates;return !p||Array.isArray(p)||!p[u]?W(`add_gate write verification failed: gate "${u}" not found in ${l} after write.`):(await s(),z({action:"add_gate",file:l,id:u,symbol:`^${u}`}))}async function Dc(t,e,s){let{purposeFile:n,id:r,description:i,type:o,default:a,properties:c}=t,l=ee(n,e.rootDir),d=M(l);(!d.states||Array.isArray(d.states))&&(d.states={});let u=H(r),p={description:i};o!==void 0&&(p.type=o),a!==void 0&&(p.default=a),c!==void 0&&(p.properties=c),d.states[u]=p,we(l,d);let g=M(l).states;return !g||Array.isArray(g)||!g[u]?W(`add_state write verification failed: state "${u}" not found in ${l} after write.`):(await s(),z({action:"add_state",file:l,id:u}))}async function $c(t,e,s){let{purposeFile:n,componentId:r,section:i,signals:o,aspects:a,gates:c,flows:l,components:d}=t,u=ee(n,e.rootDir),p=M(u),g=H(r),m=i;if(!m){let b=Pe(p.components),w=Pe(p.features);if(g in b)m="components";else if(g in w)m="features";else return W(`Component "${g}" not found in components or features. Specify section explicitly.`)}let y=Pe(p[m]);if(!(g in y))return W(`Component "${g}" not found in ${m} section.`);let f=y[g];o&&(f.signals=Ee(f.signals,o.map(b=>F(b,"!")))),c&&(f.gates=Ee(f.gates,c.map(b=>F(b,"^")))),l&&(f.flows=Ee(f.flows,l.map(b=>F(b,"$")))),d&&(f.components=Ee(f.components,d.map(b=>F(b,"#")))),a&&(f.aspects=Ee(f.aspects,a.map(b=>F(b,"~")))),y[g]=f,p[m]=y;let v=await Ft(u,p,b=>{let w=b[m];return !w||typeof w!="object"||Array.isArray(w)?!1:g in w},m);await s();let h=[];return o&&h.push(`signals: ${o.join(", ")}`),a&&h.push(`aspects: ${a.join(", ")}`),c&&h.push(`gates: ${c.join(", ")}`),l&&h.push(`flows: ${l.join(", ")}`),d&&h.push(`components: ${d.join(", ")}`),z({action:"link",file:v.path,componentId:g,section:m,added:h,written:v.written,hashHint:v.hashHint,bytes:v.bytes})}async function Hc(t,e,s){let{purposeFile:n,section:r,id:i}=t,o=ee(n,e.rootDir),a=M(o),c=H(i);if(r==="flows"){let d=Ne(a.flows);if(!(c in d))return W(`Flow "${c}" not found in flows section.`);delete d[c],a.flows=d;}else if(r==="components"||r==="features"){let d=Pe(a[r]);if(!(c in d))return W(`"${c}" not found in ${r} section.`);delete d[c],a[r]=d;}else {let d=a[r];if(!d||!(c in d))return W(`"${c}" not found in ${r} section.`);delete d[c];}let l=await Ft(o,a,d=>{if(r==="flows"){let p=Ne(d.flows);return !(c in p)}let u=d[r];return !u||typeof u!="object"||Array.isArray(u)?!0:!(c in u)},r);return await s(),z({action:"remove",file:l.path,section:r,id:c,written:l.written,hashHint:l.hashHint,bytes:l.bytes})}async function Fc(t,e,s){let{oldId:n,newId:r,symbolType:i}=t,o=await Ei(e.rootDir,n,r,i);return await s(),z({action:"rename",oldSymbol:`${i}${H(n)}`,newSymbol:`${i}${H(r)}`,filesModified:o.length,files:o})}async function Nc(t,e,s){let{id:n,description:r,type:i,location:o,requires:a,check:c,grants:l,emits:d,prizes:u}=t,p=await Mi(e.rootDir,{id:n,description:r,type:i,location:o,requires:a,check:c,grants:l,emits:d,prizes:u});await s();let g=H(n);return z({action:"portal_add_gate",file:p.path,id:g,symbol:`^${g}`,written:p.written,hashHint:p.hashHint,bytes:p.bytes})}async function Ec(t,e,s){let{route:n,method:r,gates:i}=t,o=await Gi(e.rootDir,{route:n,method:r,gates:i});return await s(),z({action:"portal_add_route",file:o.path,route:`${r} ${n}`,gates:i,written:o.written,hashHint:o.hashHint,bytes:o.bytes})}var qc=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function Ji(t,e){let s=[];function n(i,o){if(typeof i=="string"){let a=i.match(qc);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}n(t.description,"description");let r=[{key:"components",items:t.components},{key:"features",items:t.features},{key:"gates",items:t.gates},{key:"signals",items:t.signals},{key:"aspects",items:t.aspects}];for(let i of r)if(i.items&&typeof i.items=="object")for(let[o,a]of Object.entries(i.items))a&&typeof a.description=="string"&&n(a.description,`${i.key}.${o}.description`);if(t.flows&&typeof t.flows=="object"){let i=Array.isArray(t.flows)?[]:Object.entries(t.flows);for(let[o,a]of i)a&&typeof a.description=="string"&&n(a.description,`flows.${o}.description`);}return s}async function Lc(t,e){let{purposeFile:s,includePortal:n=true}=t,r=[];if(s){let a=ee(s,e.rootDir),c=b$c(a);if(!c.data)r.push({file:a,valid:false,issues:c.errors.map(l=>({type:"error",message:l}))});else {let l=e$9(c.data,a);if(c.data.aspects)for(let[u,p]of Object.entries(c.data.aspects))(!p.anchors||p.anchors.length===0)&&(l.issues.push({type:"error",message:`Aspect "${u}" is missing required anchors`,path:`aspects.${u}`}),l.valid=false);let d=Ji(c.data);l.issues.push(...d),r.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await d$8(e.rootDir);for(let c of a){let l=b$c(c);if(!l.data){r.push({file:c,valid:false,issues:l.errors.map(p=>({type:"error",message:p}))});continue}let d=e$9(l.data,c);if(l.data.aspects)for(let[p,g]of Object.entries(l.data.aspects))(!g.anchors||g.anchors.length===0)&&(d.issues.push({type:"error",message:`Aspect "${p}" is missing required anchors`,path:`aspects.${p}`}),d.valid=false);let u=Ji(l.data);d.issues.push(...u),r.push({file:c,valid:d.valid,issues:d.issues});}}if(n){let{data:a,filePath:c}=qt(e.rootDir),l=[];if(a.gates)for(let[d,u]of Object.entries(a.gates))u.description||l.push({type:"warning",message:`Gate "${d}" has no description`,path:`gates.${d}`}),u.prizes||l.push({type:"warning",message:`Gate "${d}" is missing prizes array (v2 requirement)`,path:`gates.${d}`});l.length>0&&r.push({file:c,valid:l.every(d=>d.type!=="error"),issues:l});}let i=r.reduce((a,c)=>a+c.issues.length,0),o=r.every(a=>a.valid);return z({action:"validate",valid:o,totalFiles:r.length,totalIssues:i,results:r})}var ro=[{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}],Wc=30*1e3,Wn=new Map;function Y(t){let e=$.resolve(t),s=Wn.get(e);if(s&&Date.now()-s.loadedAt<Wc)return s.habits;let n=zc(e);return Wn.set(e,{habits:n,loadedAt:Date.now()}),n}function zc(t){let e=new Map;for(let a of ro)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",n=Ki($.join(s,".paradigm","habits.yaml"));n&&Xi(e,n);let r=Qi($.join(s,".paradigm","habits"));for(let a of r)e.set(a.id,a);let i=Ki($.join(t,".paradigm","habits.yaml"));i&&Xi(e,i);let o=Qi($.join(t,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function Ki(t){if(!A.existsSync(t))return null;try{let e=A.readFileSync(t,"utf8");return qe.load(e)}catch{return null}}function Xi(t,e){if(e.habits)for(let s of e.habits)t.set(s.id,{...s});if(e.overrides)for(let[s,n]of Object.entries(e.overrides)){let r=t.get(s);r&&(n.severity!==void 0&&(r.severity=n.severity),n.enabled!==void 0&&(r.enabled=n.enabled));}}function Bc(t,e){return t.filter(s=>s.enabled&&s.trigger===e)}function zn(t){Wn.delete($.resolve(t));}function Qi(t){if(!A.existsSync(t))return [];try{let e=A.readdirSync(t).filter(n=>n.endsWith(".habit")).sort(),s=[];for(let n of e)try{let r=A.readFileSync($.join(t,n),"utf8"),i=qe.load(r);i?.id&&i?.name&&s.push(i);}catch{}return s}catch{return []}}var Zi=["discovery","verification","testing","documentation","collaboration","security"],eo=["preflight","postflight","on-commit","on-stop"],to=["advisory","warn","block"],no=["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"],Vc=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Bn(t){let e=[];if(t.id||e.push("Missing required field: id"),t.name||e.push("Missing required field: name"),t.description||e.push("Missing required field: description"),t.category||e.push("Missing required field: category"),t.trigger||e.push("Missing required field: trigger"),t.severity||e.push("Missing required field: severity"),t.check||e.push("Missing required field: check"),(t.enabled===void 0||t.enabled===null)&&e.push("Missing required field: enabled"),t.id&&!Vc.test(t.id)&&e.push(`Invalid id format: "${t.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),t.category&&!Zi.includes(t.category)&&e.push(`Invalid category: "${t.category}" \u2014 must be one of: ${Zi.join(", ")}`),t.trigger&&!eo.includes(t.trigger)&&e.push(`Invalid trigger: "${t.trigger}" \u2014 must be one of: ${eo.join(", ")}`),t.severity&&!to.includes(t.severity)&&e.push(`Invalid severity: "${t.severity}" \u2014 must be one of: ${to.join(", ")}`),t.check){no.includes(t.check.type)||e.push(`Invalid check.type: "${t.check.type}" \u2014 must be one of: ${no.join(", ")}`);let s=t.check.params||{};switch(t.check.type){case "tool-called":(!s.tools||!Array.isArray(s.tools)||s.tools.length===0)&&e.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!s.patterns||!Array.isArray(s.patterns)||s.patterns.length===0)&&e.push(`check.type "${t.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!s.messagePatterns||!Array.isArray(s.messagePatterns)||s.messagePatterns.length===0)&&e.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:e.length===0,errors:e}}var Yc=new Set(ro.map(t=>t.id));function zt(t){return Yc.has(t)}function Vn(t,e,s="project"){let n=s==="global"?$.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):$.join(t,".paradigm","habits");A.existsSync(n)||A.mkdirSync(n,{recursive:true});let r=$.join(n,`${e.id}.habit`),i=qe.dump(e,{lineWidth:120,noRefs:true});return A.writeFileSync(r,i,"utf8"),zn(t),r}function so(t,e){if(zt(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=$.join(t,".paradigm","habits",`${e}.habit`);if(A.existsSync(s))return A.unlinkSync(s),zn(t),{removed:true};let n=process.env.HOME||process.env.USERPROFILE||"~",r=$.join(n,".paradigm","habits",`${e}.habit`);return A.existsSync(r)?(A.unlinkSync(r),zn(t),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var Yn=0;function gt(t,e,s,n,r){let i=Bc(t,e);n&&(i=i.filter(p=>!p.platforms||p.platforms.includes(n)));let o=0;if(r)try{let{isGraduated:p}=(Wt(),d$a(Yi)),g=i.length;i=i.filter(m=>!p(r,m.id)),o=g-i.length;}catch{}Yn=o;let a=i.map(p=>Kc(p,s)),c=a.filter(p=>p.result==="followed").length,l=a.filter(p=>p.result==="skipped").length,d=a.filter(p=>p.result==="partial").length,u=a.filter(p=>p.result==="skipped"&&p.habit.severity==="block").length;return {trigger:e,evaluations:a,summary:{total:a.length,followed:c,skipped:l,partial:d,blockingViolations:u},blocksCompletion:u>0}}function ft(t){return {toolsCalled:t.toolsCalled||[],filesModified:t.filesModified||[],symbolsTouched:t.symbolsTouched||[],loreRecorded:t.loreRecorded||false,hasPortalRoutes:t.hasPortalRoutes||false,taskAddsRoutes:t.taskAddsRoutes||false,taskDescription:t.taskDescription,gitClean:t.gitClean}}function Kc(t,e){switch(t.check.type){case "tool-called":return Xc(t,e);case "file-exists":return Qc(t,e);case "file-modified":return rl(t,e);case "lore-recorded":return Zc(t,e);case "symbols-registered":return el(t,e);case "gates-declared":return tl(t,e);case "tests-exist":return nl(t,e);case "git-clean":return sl(t,e);case "commit-message-format":return il(t,e);case "flow-coverage":return ol(t,e);case "context-checked":return al(t,e);case "aspect-anchored":return cl(t,e);default:return {habit:t,result:"partial",reason:`Unknown check: ${t.check.type}`}}}function Xc(t,e){let s=t.check.params.tools||[];if(s.length===0)return {habit:t,result:"followed",reason:"No tools required"};let n=s.filter(r=>e.toolsCalled.includes(r));return n.length>0?{habit:t,result:"followed",reason:`Called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, habit not applicable"}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function Qc(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};if(e.filesModified.some(r=>r.endsWith(".purpose")||r.includes(".paradigm/")))return {habit:t,result:"followed",reason:"Purpose files updated"};let n=e.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 n.length===0?{habit:t,result:"followed",reason:"Only non-source files modified"}:{habit:t,result:"skipped",reason:`${n.length} source file(s) without .purpose updates`,evidence:n.slice(0,5)}}function Zc(t,e){let s=e.filesModified.filter(n=>!n.endsWith(".md")&&!n.endsWith(".json")&&!n.endsWith(".yaml")&&!n.endsWith(".yml")&&!n.endsWith(".lock")&&!n.endsWith(".purpose")&&!n.includes(".paradigm/"));return s.length<3?{habit:t,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:t,result:"followed",reason:"Lore recorded"}:{habit:t,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function el(t,e){if(e.symbolsTouched.length===0)return {habit:t,result:"followed",reason:"No symbols touched"};let n=["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=>e.toolsCalled.includes(r));return n.length>0?{habit:t,result:"followed",reason:`Purpose tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function tl(t,e){if(!e.taskAddsRoutes)return {habit:t,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:t,result:"followed",reason:"Portal.yaml has routes"};let n=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(r=>e.toolsCalled.includes(r));return n.length>0?{habit:t,result:"followed",reason:`Gate tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:"Routes added without gate declarations"}}function nl(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=e.filesModified.filter(r=>r.includes(".test.")||r.includes(".spec.")||r.includes("/tests/")||r.includes("/test/")||r.includes("__tests__"));if(s.length>0)return {habit:t,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let n=e.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 n.length===0?{habit:t,result:"followed",reason:"No source files to test"}:{habit:t,result:"partial",reason:`${n.length} source file(s), no test files updated`,evidence:n.slice(0,5)}}function rl(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=t.check.params.patterns||[];if(s.length===0)return {habit:t,result:"followed",reason:"No patterns specified"};if(t.trigger==="on-stop"&&t.severity==="block"){let r=e.filesModified.filter(i=>s.some(o=>i.includes(o)||$.basename(i)===o));return r.length>0?{habit:t,result:"followed",reason:`Matching files: ${r.join(", ")}`,evidence:r}:{habit:t,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let n=e.filesModified.filter(r=>s.some(i=>r.includes(i)||$.basename(r)===i));return n.length>0?{habit:t,result:"followed",reason:`Matching files: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function sl(t,e){return e.filesModified.length===0?{habit:t,result:"followed",reason:"No files modified"}:t.trigger==="on-stop"?{habit:t,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:t,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:t,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:t,result:"skipped",reason:"Uncommitted changes in working tree"}}function il(t,e){if(!e.commitMessage)return {habit:t,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=t.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],n=s.filter(r=>new RegExp(r,"m").test(e.commitMessage));if(n.length===s.length)return {habit:t,result:"followed",reason:"Commit message matches all required patterns",evidence:n};if(n.length>0){let r=s.filter(i=>!new RegExp(i,"m").test(e.commitMessage));return {habit:t,result:"partial",reason:`Matches ${n.length}/${s.length} patterns. Missing: ${r.join(", ")}`}}return {habit:t,result:"skipped",reason:"Commit message does not match required format patterns"}}function ol(t,e){let s=e.symbolsTouched.filter(i=>i.startsWith("#"));if(s.length<3)return {habit:t,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:t,result:"followed",reason:"Flow coverage exists for multi-component changes"};let r=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(i=>e.toolsCalled.includes(i));return r.length>0?{habit:t,result:"followed",reason:`Flow tools called: ${r.join(", ")}`,evidence:r}:{habit:t,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function al(t,e){let n=(t.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(r=>e.toolsCalled.includes(r));return n.length>0?{habit:t,result:"followed",reason:`Context tools called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, context check not applicable"}:{habit:t,result:"skipped",reason:"No context/session tools called during session"}}function cl(t,e){let s=e.symbolsTouched.filter(n=>n.startsWith("~"));return s.length===0?{habit:t,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:t,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:t,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:t,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var ll={"missing-purpose":t=>`${t.target?`"${t.target}"`:"a directory"} is missing a .purpose file. Without it, agents cannot discover what this directory contains or which components live here. The stop hook will block if source files were modified in a directory with no .purpose. Fix: run paradigm_purpose_init for this directory, then add components with paradigm_purpose_add_component.`,"stale-purpose":t=>{let e=t.target?`"${t.target}"`:"a .purpose file",s=t.context?.ageHours!=null?` (${t.context.ageHours}h old)`:"";return `The .purpose file at ${e}${s} has not been updated since the last code change in its directory. Stale purposes mislead agents about what components exist, causing incorrect context injection. Fix: update the .purpose to reflect any added, removed, or changed components, then run paradigm_reindex.`},"missing-gate":t=>`${t.target?`"${t.target}"`:"a route or endpoint"} appears to require authentication or authorization but has no gate declared in portal.yaml. Gates are how Paradigm tracks security enforcement \u2014 missing gates mean agents cannot verify that the route is protected. Fix: add the gate to portal.yaml using paradigm_portal_add_route or paradigm_purpose_add_component with the appropriate gates array.`,"orphan-signal":t=>`${t.target?`"${t.target}"`:"a signal"} is emitted in code but not declared in any .purpose file. Undeclared signals cannot be traced by agents during ripple analysis, meaning downstream effects may be missed when the signal's emitter changes. Fix: add the signal to the nearest .purpose file under its component's signals array (e.g., signals: ["!${t.target||"event-name"}"]). `,"undocumented-flow":t=>`${t.target?`"${t.target}"`:"a multi-step flow"} spans multiple components but has no $flow declaration. Flows with 3 or more steps should be documented so agents can reason about the sequence end-to-end. Without a flow record, agents may implement duplicate logic or miss ordering constraints. Fix: add a flow entry to .paradigm/flows.yaml with the steps and participants.`,"aspect-drift":t=>`${t.target?`"${t.target}"`:"an aspect anchor"} has drifted \u2014 the code at the anchored location no longer matches the fingerprint recorded when the aspect was first applied. This means the aspect may no longer be enforced correctly at that site. Drift is common after refactors that move or rewrite anchored code. Fix: re-anchor the aspect at its new location using paradigm_aspect_anchor, then delete the stale anchor.`,"portal-mismatch":t=>`${t.target?`"${t.target}"`:"a portal.yaml entry"} has a mismatch between what portal.yaml declares and what the code enforces. This could mean a gate is declared but never applied in middleware, or code enforces a check that is not tracked in portal.yaml. Both directions create audit gaps. Fix: reconcile portal.yaml with actual middleware usage \u2014 run paradigm portal check to see specifics.`,"missing-test":t=>`${t.target?`"${t.target}"`:"a component"} has no associated test file. Agents are expected to write tests alongside every implementation. Missing tests increase regression risk and reduce confidence scores for the affected component. Fix: create a test file alongside the implementation (e.g., ${t.target?t.target.replace(/\.[^.]+$/,".test$&"):"component.test.ts"}).`,"uncovered-route":t=>`${t.target?`"${t.target}"`:"a route"} appears in the codebase but is not listed in portal.yaml. All routes \u2014 protected or public \u2014 should be tracked in portal.yaml so the full API surface is visible to agents and reviewers. Uncovered routes are invisible to ripple analysis and gate audits. Fix: add the route to portal.yaml with paradigm_portal_add_route.`,"broken-reference":t=>`${t.target?`"${t.target}"`:"a symbol reference"} references a symbol or file that no longer exists. Broken references in .purpose files cause agents to load stale context and may indicate a renamed or deleted component. Fix: update the reference to the new symbol name, or remove it if the component was deleted. Run paradigm_reindex after fixing to regenerate the scan index.`,"missing-description":t=>`${t.target?`"${t.target}"`:"a component or gate"} has no description. Descriptions are required for agents to understand purpose and context during context injection. Without descriptions, agents may misapply the component or skip it when it would have been relevant. Fix: add a description field to the component or gate entry in its .purpose or portal.yaml file.`,"enforcement-level-violation":t=>{let e=t.target?`"${t.target}"`:"a data category",s=t.context?.ring,n=t.context?.boundary;return `${e} is being transmitted across a boundary (${n||"unknown boundary"}) that exceeds its trust ring${s?` (Ring: ${s})`:""}. Data policy requires project-locked content to never leave the project boundary. This gap could expose internal compliance data externally. Fix: check the data-policy.yaml configuration and ensure the content category is listed in the deny_content for the relevant stream.`},"index-stale":t=>{let e=t.target?`"${t.target}"`:"the scan index",s=t.context?.ageHours,n=s!=null?` (${s} hours old)`:"";return `${e}${n} is stale. The scan index drives context injection, navigator, and ripple analysis. When the index is out of date, agents work from stale symbol maps and may miss recently added components or references. Fix: run paradigm_reindex (or "paradigm index") to regenerate the index.`}};function dl(t,e){let s=ll[t];return s?s({...e,type:t}):`Unknown check type "${t}" \u2014 no narration template available.`}function oo(t){let e=[],s=[],n=[];for(let o of t){let a=dl(o.type,o),c=o.severity??"improvement",l={type:o.type,target:o.target,narration:a,severity:c};c==="blocking"?e.push(l):c==="note"?n.push(l):s.push(l);}let r=e.length+s.length+n.length,i=pl(e,s,n);return {gapCount:r,blocking:e,improvement:s,note:n,narrative:i}}function pl(t,e,s){let n=[],r=t.length+e.length+s.length;if(r===0)return "No gaps found. All enforcement checks passed.";if(n.push(`Found ${r} gap${r!==1?"s":""} across ${io(t,e,s)} check type${io(t,e,s)!==1?"s":""}.`),n.push(""),t.length>0){n.push(`BLOCKING (${t.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let i of t)n.push(`[${i.type}]${i.target?` \u2014 ${i.target}`:""}`),n.push(i.narration),n.push("");}if(e.length>0){n.push(`IMPROVEMENTS (${e.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let i of e)n.push(`[${i.type}]${i.target?` \u2014 ${i.target}`:""}`),n.push(i.narration),n.push("");}if(s.length>0){n.push(`NOTES (${s.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500");for(let i of s)n.push(`[${i.type}]${i.target?` \u2014 ${i.target}`:""}`),n.push(i.narration),n.push("");}return n.join(`
63
+ `)[0].trim()||""});return {handled:true,text:JSON.stringify({query:r,count:l.length,matches:l},null,2)}}if(n==="get"){if(!i)return {handled:true,text:JSON.stringify({error:"Tag name required for get action"})};if(a.core?.[i]){let l=a.core[i];return {handled:true,text:JSON.stringify({tag:i,category:"core",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}if(a.project?.[i]){let l=a.project[i];return {handled:true,text:JSON.stringify({tag:i,category:"project",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}let c=a.suggested?.find(l=>l.tag===i);return c?{handled:true,text:JSON.stringify({tag:i,category:"suggested",reason:c.reason,proposedBy:c["proposed-by"],proposedAt:c["proposed-at"],appliesTo:c["applies-to"],exampleSymbols:c["example-symbols"],status:"pending approval"},null,2)}:{handled:true,text:JSON.stringify({error:`Tag "${i}" not found`,suggestion:'Use paradigm_tags with action "list" to see available tags'})}}return {handled:true,text:JSON.stringify({error:`Unknown action: ${n}`})}}case "paradigm_tags_suggest":{let{tag:n,description:r,reason:i,appliesTo:o,exampleSymbols:a}=e,c=$i(s.rootDir);if(!c)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml first"})};if(c.core?.[n]||c.project?.[n])return {handled:true,text:JSON.stringify({error:`Tag "${n}" already exists`,existing:c.core?.[n]?"core":"project"})};if(c.suggested?.some(d=>d.tag===n))return {handled:true,text:JSON.stringify({error:`Tag "${n}" is already in the suggested queue`,status:"pending approval"})};let l={tag:n,"proposed-by":"claude","proposed-at":new Date().toISOString(),reason:i,"applies-to":o||["#"],"example-symbols":a};return c.suggested||(c.suggested=[]),c.suggested.push(l),sc(s.rootDir,c),{handled:true,text:JSON.stringify({success:true,tag:n,status:"pending approval",message:"Tag suggestion added. Human review required before use.",nextSteps:["Human can approve via Sentinel UI or CLI",'Once approved, tag moves to "project" section',"Then AI can use the tag for classification"]},null,2)}}case "paradigm_aspect_check":{let{aspect:n}=e,r=n.startsWith("~")?n:`~${n}`,i=k(s.index,r);if(!i)return {handled:true,text:JSON.stringify({error:`Aspect "${r}" not found`,suggestion:"Use paradigm_search to find available aspects"})};if(i.type!=="aspect")return {handled:true,text:JSON.stringify({error:`Symbol "${r}" is not an aspect (type: ${i.type})`,note:"Only ~ symbols are aspects"})};let o=i.anchors||[],a=i.filePath?$.isAbsolute(i.filePath)?i.filePath:$.resolve(s.rootDir,i.filePath):s.rootDir,c=i.filePath?$.dirname(a):s.rootDir,l=[];for(let f of o){let v=r$1(f.path,c,s.rootDir),h=v.resolvedPath,b=v.exists,w;if(b)try{let _=I.readFileSync(h,"utf-8").split(`
64
+ `);typeof f.lines=="number"?w=1:Array.isArray(f.lines)&&f.lines.length===2?w=f.lines[1]-f.lines[0]+1:Array.isArray(f.lines)&&(w=f.lines.length);}catch{}let x;b||s$1(f.path,c,s.rootDir).mismatch&&(x="Anchor resolves under .purpose-dir base but not project-root base (or vice versa). This indicates a framework path-resolution bug; do NOT hand-edit. Run `paradigm_aspect_drift` for full audit, or file framework-bug task per protocol."),l.push({path:f.path,lines:f.raw.split(":")[1]||"full file",exists:b,lineCount:w,...x?{resolution_hint:x}:{}});}let d=o.length>0&&l.every(f=>f.exists),u=i.appliesTo||[],p=q(s.index),g=[],m=[];for(let f of p)for(let v of u)if(new RegExp("^"+v.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(f.symbol)){g.push(f.symbol),(f.data?.aspects?.includes?.(r)||f.data?.aspects?.includes?.(n))&&m.push(f.symbol);break}let y=g.filter(f=>!m.includes(f));return {handled:true,text:JSON.stringify({aspect:r,valid:d,description:i.description,enforcement:i.enforcement,anchors:l,coverage:{appliesTo:u,matchingSymbols:g.length,symbolsWithAspect:m.length,missing:y.slice(0,10),missingCount:y.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...l.filter(f=>!f.exists).map(f=>`Anchor file not found: ${f.path}`),...y.length>0?[`${y.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:d?y.length>0?"Aspect is valid but has coverage gaps - consider applying to matching symbols":"Aspect is valid and fully applied":"INVALID: Add code anchors to this aspect"},null,2)}}default:return {handled:false,text:""}}}b$1();var re=class extends Error{code="WRITE_VERIFICATION_FAILED";constructor(e="write verification failed"){super(e),this.name="WriteVerificationError";}},ic=".paradigm-install-key",oc="paradigm-v5.38.0-hmac-fallback-key",we=null;function ac(){if(we)return we;try{let t=Ni.homedir(),e=$.join(t,ic);if(I.existsSync(e)){let n=I.readFileSync(e,"utf-8").trim();if(/^[0-9a-f]{64}$/i.test(n))return we=Buffer.from(n,"hex"),we}let s=ct.randomBytes(32);try{I.writeFileSync(e,s.toString("hex"),{encoding:"utf-8",mode:384});}catch{}return we=s,we}catch{return we=Buffer.from(oc),we}}function cc(t){let e=ct.createHmac("sha256",ac());return e.update(t),e.digest("hex").slice(0,12)}function lc(t,e){let s=$.dirname(t),n=`.${$.basename(t)}.${process.pid}.${Date.now()}.${ct.randomBytes(4).toString("hex")}.tmp`,r=$.join(s,n);try{I.writeFileSync(r,e,{encoding:"utf-8"}),I.renameSync(r,t);}catch(i){try{I.unlinkSync(r);}catch{}throw i}}async function lt(t,e,s){lc(t,e);let n;try{n=I.readFileSync(t,"utf-8");}catch{throw a.component("#write-and-confirm").error("read-back failed after atomic write",{stage:"read-back"}),new re("write verification failed (read-back error)")}let r=false;try{r=s(n);}catch{throw a.component("#write-and-confirm").error("verify callback threw",{stage:"verify-callback",strict:b$d()}),new re("write verification failed (verify callback error)")}if(!r)throw a.component("#write-and-confirm").error("verify callback returned false",{stage:"verify-callback-false",strict:b$d()}),new re("write verification failed");let i=Buffer.byteLength(n,"utf-8"),o=cc(n);return {written:true,path:t,hashHint:o,bytes:i}}b$1();var dc=["#","$","^","!","~"];function H(t){return t.length>1&&dc.includes(t[0])?t.slice(1):t}function F(t,e){let s=H(t);return `${e}${s}`}function ee(t,e){let s=$.isAbsolute(t)?t:$.resolve(e,t);return s.endsWith(".purpose")?s:$.join(s,".purpose")}function M(t){if(!I.existsSync(t))return {};let e=b$c(t);if(!e.data)throw new Error(`Failed to parse ${t}: ${e.errors.join(", ")}`);return e.data}function ke(t,e){let s=$.dirname(t);I.existsSync(s)||I.mkdirSync(s,{recursive:true});let n=c$7(e);I.writeFileSync(t,n,"utf8");}async function Ft(t,e,s,n="purpose.yaml"){let r=$.dirname(t);I.existsSync(r)||I.mkdirSync(r,{recursive:true});let i=c$7(e);try{return await lt(t,i,o=>{let a=b$c(t);if(!a.data)return !1;try{return s(a.data)}catch{return !1}})}catch(o){throw o instanceof re?(a.component("#purpose-writer").error("purpose write verification failed",{surface:n,stage:"writeAndConfirm"}),new Error(`purpose write verification failed (${n})`)):o}}function Te(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t){let{id:n,...r}=s;e[n]=r;}return e}function Ne(t){if(!t)return {};if(!Array.isArray(t)){let s={};for(let[n,r]of Object.entries(t))!n||n==="undefined"||(s[n]=r);return s}let e={};for(let s of t)!s||!s.name||(e[s.name]={description:s.description,steps:s.steps});return e}function Ee(t,e){if(!e||e.length===0)return t;if(!t||t.length===0)return e;let s=new Set(t);for(let n of e)s.add(n);return Array.from(s)}var pc={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function Ei(t,e,s,n){let r=pc[n];if(!r)throw new Error(`Invalid symbol type: ${n}. Expected one of: # ^ ! $ ~`);let i=H(e),o=H(s),a=F(i,r),c=F(o,r),l=await d$8(t),d=[];for(let u of l){let p=M(u),g=false,y={"#":"components","^":"gates","!":"signals",$:"flows","~":"aspects"}[r];if(y&&y!=="flows"){let f=p[y];f&&!Array.isArray(f)&&i in f&&(f[o]=f[i],delete f[i],g=true);}if(r==="#")for(let f of ["features","components"]){let v=p[f];v&&!Array.isArray(v)&&i in v&&(v[o]=v[i],delete v[i],g=true);}r==="$"&&p.flows&&!Array.isArray(p.flows)&&i in p.flows&&(p.flows[o]=p.flows[i],delete p.flows[i],g=true);for(let f of ["features","components"]){let v=Te(p[f]);for(let[h,b]of Object.entries(v))g=uc(b,a,c)||g;g&&Object.keys(v).length>0&&(p[f]=v);}if(p.flows){let f=Ne(p.flows);for(let[v,h]of Object.entries(f)){if(h.gates){let b=h.gates.indexOf(a);b!==-1&&(h.gates[b]=c,g=true);}if(h.signals){let b=h.signals.indexOf(a);b!==-1&&(h.signals[b]=c,g=true);}if(h.components){let b=h.components.indexOf(a);b!==-1&&(h.components[b]=c,g=true);}if(h.steps)for(let b of h.steps)typeof b=="object"&&"component"in b&&(b.component===a||b.component===i)&&(b.component=r==="#"?o:c,g=true);}g&&(p.flows=f);}if(p.gates){for(let[f,v]of Object.entries(p.gates))if(v.signals){let h=v.signals.indexOf(a);h!==-1&&(v.signals[h]=c,g=true);}}if(p.aspects){for(let[f,v]of Object.entries(p.aspects))if(v["applies-to"]){let h=v["applies-to"].indexOf(a);h!==-1&&(v["applies-to"][h]=c,g=true);}}g&&(ke(u,p),d.push(u));}return d}function uc(t,e,s){let n=false,r=["signals","gates","flows","components","states"];for(let i of r){let o=t[i];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,n=true);}}if(t.aspects&&Array.isArray(t.aspects)){let i=t.aspects.indexOf(e);i!==-1&&(t.aspects[i]=s,n=true);}return n}b$1();function gc(t){return h$7(t)}function Et(t,e){if(!I.existsSync(t))return {status:"missing"};let s;try{s=I.readFileSync(t,"utf-8");}catch{return qn({status:"unparseable",errorClass:"other",detail:"file read error"})}let n;try{n=qe.load(s);}catch(r){let{errorClass:i,detail:o}=gc(r);return qn({status:"unparseable",errorClass:i,detail:o})}return {status:"ok",data:n}}function qn(t,e){if(!(b$d())||t.status==="ok"||t.status==="missing")return t;throw new Error(`yaml load failed under PARADIGM_STRICT=1 (${t.errorClass}: ${t.detail})`)}function qt(t){let e=$.join(t,"portal.yaml"),s=Et(e);if(s.status==="missing")return {data:{version:"1.0.0",gates:{}},filePath:e};if(s.status==="unparseable"||s.status==="invalid")throw a.component("#portal-writer").error("portal.yaml unparseable on read",{errorClass:s.errorClass}),new Error(`portal.yaml unparseable (${s.errorClass}). Refusing to overwrite. Run 'paradigm doctor' for line-specific details.`);return {data:s.data||{version:"1.0.0",gates:{}},filePath:e}}async function Mi(t,e){let{data:s,filePath:n}=qt(t);if(!s.gates||Array.isArray(s.gates)){let a=s.gates;if(s.gates={},Array.isArray(a)&&a.length>0){for(let c of a)if(c&&typeof c=="object"&&"id"in c){let l=H(c.id);s.gates[l]=c;}}}let r=H(e.id),i=s.gates[r]||{};i.description=e.description,e.type!==void 0&&(i.type=e.type),e.location!==void 0&&(i.location=e.location),e.requires!==void 0&&(i.requires=e.requires),e.check!==void 0&&(i.check=e.check),e.grants!==void 0&&(i.grants=e.grants),e.emits!==void 0&&(i.emits=e.emits),e.prizes!==void 0&&(i.prizes=e.prizes),i.prizes||(i.prizes=[]),s.gates[r]=i;let o=qe.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await lt(n,o,a=>{let c;try{c=qe.load(a);}catch{return !1}let l=c?.gates;return !l||Array.isArray(l)?!1:!!l[r]})}catch(a$1){throw a$1 instanceof re?(a.component("#portal-writer").error("portal_add_gate write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_gate write verification failed")):a$1}}async function Gi(t,e){let{data:s,filePath:n}=qt(t);(!s.routes||Array.isArray(s.routes))&&(s.routes={});let r=`${e.method} ${e.route}`,i=e.gates.map(a=>`^${H(a)}`);s.routes[r]=i;let o=qe.dump(s,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});try{return await lt(n,o,a=>{let c;try{c=qe.load(a);}catch{return !1}let l=c?.routes;return !l||Array.isArray(l)?!1:!!l[r]})}catch(a$1){throw a$1 instanceof re?(a.component("#portal-writer").error("portal_add_route write verification failed",{stage:"writeAndConfirm"}),new Error("portal_add_route write verification failed")):a$1}}var fc={name:"paradigm_purpose_init",description:"Create or update file-level metadata on a .purpose file. Does NOT overwrite existing components/signals/etc \u2014 only touches top-level metadata (name, description, context, version). ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory (relative to project root)"},name:{type:"string",description:"Name/title for this purpose file"},description:{type:"string",description:"Description of what this directory/module does"},context:{type:"array",items:{type:"string"},description:"Context notes for AI agents"},version:{type:"string",description:'Version string (default: "1.0.0")'}},required:["purposeFile","name"]},annotations:{readOnlyHint:false,destructiveHint:false}},mc={name:"paradigm_purpose_add_component",description:"Add or update a component (#) or feature in a .purpose file. Strips # prefix from id automatically. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Component ID (e.g. "payment-service" or "#payment-service")'},description:{type:"string",description:"What this component does"},section:{type:"string",enum:["components","features"],description:'Which section to add to (default: "components")'},file:{type:"string",description:"Source file path for this component"},status:{type:"string",description:'Component status (e.g. "active", "deprecated")'},endpoints:{type:"array",items:{type:"string"},description:'API endpoints (e.g. ["POST /api/payments"])'},tests:{type:"array",items:{type:"string"},description:"Test file paths"},flows:{type:"array",items:{type:"string"},description:'Flow references (e.g. ["$checkout-flow"])'},gates:{type:"array",items:{type:"string"},description:'Gate references (e.g. ["^authenticated"])'},signals:{type:"array",items:{type:"string"},description:'Signal references (e.g. ["!payment-completed"])'},aspects:{type:"array",items:{type:"string"},description:'Aspect references (e.g. ["~audit-required"])'},components:{type:"array",items:{type:"string"},description:'Component references (e.g. ["#stripe-service"])'},type:{type:"string",description:'Component type (e.g., "view", "service", "model", "tool"). Open string per project vocabulary.'},parent:{type:"string",description:'Parent component (e.g., "#payment-page"). Establishes hierarchy.'}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},yc={name:"paradigm_purpose_add_aspect",description:'Add or update an aspect (~) with ENFORCED anchors. Anchors are required and must point to code locations. Strips ~ prefix automatically. This prevents the common "~aspect:name" format error. ~100 tokens.',inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Aspect ID (e.g. "audit-required" or "~audit-required")'},description:{type:"string",description:"What this aspect enforces"},anchors:{type:"array",items:{type:"string"},description:'REQUIRED. Code anchor locations (e.g. ["src/middleware/audit.ts:15-35"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g. ["compliance", "security"])'},appliesTo:{type:"array",items:{type:"string"},description:'Glob patterns for symbols this applies to (e.g. ["#*Service"])'},enforcement:{type:"string",description:'How this aspect is enforced (e.g. "middleware", "decorator")'}},required:["purposeFile","id","description","anchors"]},annotations:{readOnlyHint:false,destructiveHint:false}},hc={name:"paradigm_purpose_add_signal",description:"Add a signal (!) definition. Handles YAML ! quoting automatically. Strips ! prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Signal ID (e.g. "payment-completed" or "!payment-completed")'},description:{type:"string",description:"What this signal represents"},category:{type:"string",description:'Signal category (e.g. "business", "system", "security")'},severity:{type:"string",enum:["info","warn","error"],description:"Severity level"},emitters:{type:"array",items:{type:"string"},description:'Components that emit this signal (e.g. ["#payment-service"])'},related:{type:"array",items:{type:"string"},description:"Related signals or symbols"},data:{type:"object",description:"Schema/shape of data emitted with this signal"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},bc={name:"paradigm_purpose_add_flow",description:"Add a flow ($) definition. Strips $ prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Flow ID (e.g. "checkout-flow" or "$checkout-flow")'},description:{type:"string",description:"What this flow does"},gates:{type:"array",items:{type:"string"},description:"Gate references in this flow"},signals:{type:"array",items:{type:"string"},description:"Signals emitted during this flow"},components:{type:"array",items:{type:"string"},description:"Components involved in this flow"},steps:{type:"array",items:{type:"object",properties:{component:{type:"string"},action:{type:"string"},description:{type:"string"}},required:["component","action"]},description:"Ordered steps in the flow"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},vc={name:"paradigm_purpose_add_gate",description:"Add a gate (^) to a .purpose file's gates section. This is for purpose-level gates, NOT portal.yaml. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},requires:{type:"array",items:{type:"string"},description:"Requirements for this gate"},keys:{type:"array",items:{type:"string"},description:"Key expressions for gate evaluation"},signals:{type:"array",items:{type:"string"},description:"Signals emitted by this gate (e.g. on pass/fail)"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},wc={name:"paradigm_purpose_add_state",description:"Add a state definition to a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'State ID (e.g. "user-store")'},description:{type:"string",description:"What this state represents"},type:{type:"string",description:'Type of state (e.g. "object", "array", "string")'},default:{description:"Default value for the state"},properties:{type:"object",description:"State properties as {name: {type, description}}"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},kc={name:"paradigm_purpose_link",description:"Add references to an existing component without rewriting all fields. Merges into existing arrays (no clobber). Example: add ~rate-limited to #payment-service's aspects. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},componentId:{type:"string",description:"Component or feature ID to add references to"},section:{type:"string",enum:["components","features"],description:"Which section the component is in (default: auto-detect)"},signals:{type:"array",items:{type:"string"},description:"Signal references to add"},aspects:{type:"array",items:{type:"string"},description:"Aspect references to add"},gates:{type:"array",items:{type:"string"},description:"Gate references to add"},flows:{type:"array",items:{type:"string"},description:"Flow references to add"},components:{type:"array",items:{type:"string"},description:"Component references to add"}},required:["purposeFile","componentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},_c={name:"paradigm_purpose_remove",description:"Remove any element by section + id from a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},section:{type:"string",enum:["components","features","gates","signals","aspects","flows","states"],description:"Which section to remove from"},id:{type:"string",description:"ID of the element to remove"}},required:["purposeFile","section","id"]},annotations:{readOnlyHint:false,destructiveHint:true}},Sc={name:"paradigm_purpose_rename",description:"Rename a symbol across ALL .purpose files in the project. Updates both definitions and references. ~200 tokens.",inputSchema:{type:"object",properties:{oldId:{type:"string",description:'Current symbol ID (e.g. "payment-service")'},newId:{type:"string",description:'New symbol ID (e.g. "billing-service")'},symbolType:{type:"string",enum:["#","^","!","$","~"],description:"Symbol type prefix"}},required:["oldId","newId","symbolType"]},annotations:{readOnlyHint:false,destructiveHint:false}},xc={name:"paradigm_portal_add_gate",description:"Add or update a gate (^) in portal.yaml. Creates portal.yaml if it doesn't exist. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},type:{type:"string",description:'Gate type (e.g. "auth", "role", "ownership")'},location:{type:"string",description:'Where the gate is checked in your code (e.g. "middleware", "route-handler")'},requires:{type:"array",items:{type:"string"},description:"Prerequisite gates"},check:{type:"string",description:'Expression to evaluate (e.g. "req.user != null")'},grants:{type:"array",items:{type:"string"},description:"What passing this gate grants access to"},emits:{type:"array",items:{type:"string"},description:"Signals emitted when gate is checked"},prizes:{type:"array",items:{type:"object",properties:{id:{type:"string"},oneTime:{type:"boolean"}},required:["id"]},description:"Side effects triggered on pass"}},required:["id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Cc={name:"paradigm_portal_add_route",description:"Add a route with gates to portal.yaml. Creates routes section if needed. ~100 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:'Route path (e.g. "/api/users/:id")'},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},gates:{type:"array",items:{type:"string"},description:'Gate IDs to apply (e.g. ["^authenticated", "^user-owner"])'}},required:["route","method","gates"]},annotations:{readOnlyHint:false,destructiveHint:false}},Rc={name:"paradigm_purpose_validate",description:"Validate .purpose files and portal.yaml. Returns issues found. If no purposeFile specified, validates all files. ~200 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Specific .purpose file to validate (validates all if omitted)"},includePortal:{type:"boolean",description:"Also validate portal.yaml (default: true)"}}},annotations:{readOnlyHint:true,destructiveHint:false}};function Ui(){return [fc,mc,yc,hc,bc,vc,wc,kc,_c,Sc,xc,Cc,Rc]}async function Wi(t,e,s,n){switch(t){case "paradigm_purpose_init":return Tc(e,s,n);case "paradigm_purpose_add_component":return Pc(e,s,n);case "paradigm_purpose_add_aspect":return jc(e,s,n);case "paradigm_purpose_add_signal":return Oc(e,s,n);case "paradigm_purpose_add_flow":return Ac(e,s,n);case "paradigm_purpose_add_gate":return Ic(e,s,n);case "paradigm_purpose_add_state":return Dc(e,s,n);case "paradigm_purpose_link":return $c(e,s,n);case "paradigm_purpose_remove":return Hc(e,s,n);case "paradigm_purpose_rename":return Fc(e,s,n);case "paradigm_portal_add_gate":return Nc(e,s,n);case "paradigm_portal_add_route":return Ec(e,s,n);case "paradigm_purpose_validate":return Lc(e,s);default:return {handled:false,text:""}}}function z(t){return {handled:true,text:JSON.stringify(t,null,2)}}function W(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}async function Tc(t,e,s){let{purposeFile:n,name:r,description:i,context:o,version:a}=t,c=ee(n,e.rootDir),l=M(c);return a!==void 0?l.version=a:l.version||(l.version="1.0.0"),i!==void 0?l.description=i:l.description||(l.description=r),o!==void 0&&(l.context=o),ke(c,l),await s(),z({action:"purpose_init",file:c,metadata:{name:r,description:l.description,version:l.version}})}async function Pc(t,e,s){let{purposeFile:n,id:r,description:i,section:o="components",file:a,status:c,endpoints:l,tests:d,flows:u,gates:p,signals:g,aspects:m,components:y,type:f,parent:v}=t,h=ee(n,e.rootDir),b=M(h),w=H(r),x=o,k=Te(b[x]),_=k[w]||{description:""};_.description=i,a!==void 0&&(_.file=a),c!==void 0&&(_.status=c),l!==void 0&&(_.endpoints=l),d!==void 0&&(_.tests=d),u!==void 0&&(_.flows=u.map(C=>F(C,"$"))),p!==void 0&&(_.gates=p.map(C=>F(C,"^"))),g!==void 0&&(_.signals=g.map(C=>F(C,"!"))),m!==void 0&&(_.aspects=m.map(C=>F(C,"~"))),y!==void 0&&(_.components=y.map(C=>F(C,"#"))),f!==void 0&&(_.type=f),v!==void 0&&(_.parent=F(v,"#")),k[w]=_,b[x]=k;let P=await Ft(h,b,C=>{let j=C[x];return !j||typeof j!="object"||Array.isArray(j)?!1:w in j},x);return await s(),z({action:"add_component",file:P.path,section:x,id:w,symbol:`#${w}`,written:P.written,hashHint:P.hashHint,bytes:P.bytes})}async function jc(t,e,s){let{purposeFile:n,id:r,description:i,anchors:o,tags:a,appliesTo:c,enforcement:l}=t;if(!o||o.length===0)return W('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let f of o)if(!d.test(f))return W(`Invalid anchor format: "${f}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let u=ee(n,e.rootDir),p=$.dirname(u);for(let f of o){let v=f.replace(/:.*$/,""),h=$.resolve(p,v);if(!I.existsSync(h)){let b=$.resolve(e.rootDir,v);if(I.existsSync(b)){let w=$.relative(p,b),x=o.indexOf(f);o[x]=f.replace(v,w);}else return W(`Anchor file not found: "${v}". Anchors must be relative to the .purpose file directory (${p}).`)}}let g=M(u);(!g.aspects||Array.isArray(g.aspects))&&(g.aspects={});let m=H(r);g.aspects[m]={description:i,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},ke(u,g);let y=M(u).aspects;return !y||Array.isArray(y)||!y[m]?W(`add_aspect write verification failed: aspect "${m}" not found in ${u} after write.`):(await s(),z({action:"add_aspect",file:u,id:m,symbol:`~${m}`,anchors:o}))}async function Oc(t,e,s){let{purposeFile:n,id:r,description:i,category:o,severity:a,emitters:c,related:l,data:d}=t,u=ee(n,e.rootDir),p=M(u);(!p.signals||Array.isArray(p.signals))&&(p.signals={});let g=H(r);p.signals[g]={description:i,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(y=>F(y,"#"))},...l&&{related:l},...d&&{data:d}},ke(u,p);let m=M(u).signals;return !m||Array.isArray(m)||!m[g]?W(`add_signal write verification failed: signal "${g}" not found in ${u} after write.`):(await s(),z({action:"add_signal",file:u,id:g,symbol:`!${g}`}))}async function Ac(t,e,s){let{purposeFile:n,id:r,description:i,gates:o,signals:a,components:c,steps:l}=t,d=ee(n,e.rootDir),u=M(d),p=Ne(u.flows),g=H(r),m={description:i,...o&&{gates:o.map(f=>F(f,"^"))},...a&&{signals:a.map(f=>F(f,"!"))},...c&&{components:c.map(f=>F(f,"#"))},...l&&{steps:l}};return p[g]=m,u.flows=p,ke(d,u),Ne(M(d).flows)[g]?(await s(),z({action:"add_flow",file:d,id:g,symbol:`$${g}`})):W(`add_flow write verification failed: flow "${g}" not found in ${d} after write.`)}async function Ic(t,e,s){let{purposeFile:n,id:r,description:i,requires:o,keys:a,signals:c}=t,l=ee(n,e.rootDir),d=M(l);(!d.gates||Array.isArray(d.gates))&&(d.gates={});let u=H(r);d.gates[u]={description:i,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(g=>F(g,"!"))}},ke(l,d);let p=M(l).gates;return !p||Array.isArray(p)||!p[u]?W(`add_gate write verification failed: gate "${u}" not found in ${l} after write.`):(await s(),z({action:"add_gate",file:l,id:u,symbol:`^${u}`}))}async function Dc(t,e,s){let{purposeFile:n,id:r,description:i,type:o,default:a,properties:c}=t,l=ee(n,e.rootDir),d=M(l);(!d.states||Array.isArray(d.states))&&(d.states={});let u=H(r),p={description:i};o!==void 0&&(p.type=o),a!==void 0&&(p.default=a),c!==void 0&&(p.properties=c),d.states[u]=p,ke(l,d);let g=M(l).states;return !g||Array.isArray(g)||!g[u]?W(`add_state write verification failed: state "${u}" not found in ${l} after write.`):(await s(),z({action:"add_state",file:l,id:u}))}async function $c(t,e,s){let{purposeFile:n,componentId:r,section:i,signals:o,aspects:a,gates:c,flows:l,components:d}=t,u=ee(n,e.rootDir),p=M(u),g=H(r),m=i;if(!m){let b=Te(p.components),w=Te(p.features);if(g in b)m="components";else if(g in w)m="features";else return W(`Component "${g}" not found in components or features. Specify section explicitly.`)}let y=Te(p[m]);if(!(g in y))return W(`Component "${g}" not found in ${m} section.`);let f=y[g];o&&(f.signals=Ee(f.signals,o.map(b=>F(b,"!")))),c&&(f.gates=Ee(f.gates,c.map(b=>F(b,"^")))),l&&(f.flows=Ee(f.flows,l.map(b=>F(b,"$")))),d&&(f.components=Ee(f.components,d.map(b=>F(b,"#")))),a&&(f.aspects=Ee(f.aspects,a.map(b=>F(b,"~")))),y[g]=f,p[m]=y;let v=await Ft(u,p,b=>{let w=b[m];return !w||typeof w!="object"||Array.isArray(w)?!1:g in w},m);await s();let h=[];return o&&h.push(`signals: ${o.join(", ")}`),a&&h.push(`aspects: ${a.join(", ")}`),c&&h.push(`gates: ${c.join(", ")}`),l&&h.push(`flows: ${l.join(", ")}`),d&&h.push(`components: ${d.join(", ")}`),z({action:"link",file:v.path,componentId:g,section:m,added:h,written:v.written,hashHint:v.hashHint,bytes:v.bytes})}async function Hc(t,e,s){let{purposeFile:n,section:r,id:i}=t,o=ee(n,e.rootDir),a=M(o),c=H(i);if(r==="flows"){let d=Ne(a.flows);if(!(c in d))return W(`Flow "${c}" not found in flows section.`);delete d[c],a.flows=d;}else if(r==="components"||r==="features"){let d=Te(a[r]);if(!(c in d))return W(`"${c}" not found in ${r} section.`);delete d[c],a[r]=d;}else {let d=a[r];if(!d||!(c in d))return W(`"${c}" not found in ${r} section.`);delete d[c];}let l=await Ft(o,a,d=>{if(r==="flows"){let p=Ne(d.flows);return !(c in p)}let u=d[r];return !u||typeof u!="object"||Array.isArray(u)?!0:!(c in u)},r);return await s(),z({action:"remove",file:l.path,section:r,id:c,written:l.written,hashHint:l.hashHint,bytes:l.bytes})}async function Fc(t,e,s){let{oldId:n,newId:r,symbolType:i}=t,o=await Ei(e.rootDir,n,r,i);return await s(),z({action:"rename",oldSymbol:`${i}${H(n)}`,newSymbol:`${i}${H(r)}`,filesModified:o.length,files:o})}async function Nc(t,e,s){let{id:n,description:r,type:i,location:o,requires:a,check:c,grants:l,emits:d,prizes:u}=t,p=await Mi(e.rootDir,{id:n,description:r,type:i,location:o,requires:a,check:c,grants:l,emits:d,prizes:u});await s();let g=H(n);return z({action:"portal_add_gate",file:p.path,id:g,symbol:`^${g}`,written:p.written,hashHint:p.hashHint,bytes:p.bytes})}async function Ec(t,e,s){let{route:n,method:r,gates:i}=t,o=await Gi(e.rootDir,{route:n,method:r,gates:i});return await s(),z({action:"portal_add_route",file:o.path,route:`${r} ${n}`,gates:i,written:o.written,hashHint:o.hashHint,bytes:o.bytes})}var qc=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function Ji(t,e){let s=[];function n(i,o){if(typeof i=="string"){let a=i.match(qc);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}n(t.description,"description");let r=[{key:"components",items:t.components},{key:"features",items:t.features},{key:"gates",items:t.gates},{key:"signals",items:t.signals},{key:"aspects",items:t.aspects}];for(let i of r)if(i.items&&typeof i.items=="object")for(let[o,a]of Object.entries(i.items))a&&typeof a.description=="string"&&n(a.description,`${i.key}.${o}.description`);if(t.flows&&typeof t.flows=="object"){let i=Array.isArray(t.flows)?[]:Object.entries(t.flows);for(let[o,a]of i)a&&typeof a.description=="string"&&n(a.description,`flows.${o}.description`);}return s}async function Lc(t,e){let{purposeFile:s,includePortal:n=true}=t,r=[];if(s){let a=ee(s,e.rootDir),c=b$c(a);if(!c.data)r.push({file:a,valid:false,issues:c.errors.map(l=>({type:"error",message:l}))});else {let l=e$9(c.data,a);if(c.data.aspects)for(let[u,p]of Object.entries(c.data.aspects))(!p.anchors||p.anchors.length===0)&&(l.issues.push({type:"error",message:`Aspect "${u}" is missing required anchors`,path:`aspects.${u}`}),l.valid=false);let d=Ji(c.data);l.issues.push(...d),r.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await d$8(e.rootDir);for(let c of a){let l=b$c(c);if(!l.data){r.push({file:c,valid:false,issues:l.errors.map(p=>({type:"error",message:p}))});continue}let d=e$9(l.data,c);if(l.data.aspects)for(let[p,g]of Object.entries(l.data.aspects))(!g.anchors||g.anchors.length===0)&&(d.issues.push({type:"error",message:`Aspect "${p}" is missing required anchors`,path:`aspects.${p}`}),d.valid=false);let u=Ji(l.data);d.issues.push(...u),r.push({file:c,valid:d.valid,issues:d.issues});}}if(n){let{data:a,filePath:c}=qt(e.rootDir),l=[];if(a.gates)for(let[d,u]of Object.entries(a.gates))u.description||l.push({type:"warning",message:`Gate "${d}" has no description`,path:`gates.${d}`}),u.prizes||l.push({type:"warning",message:`Gate "${d}" is missing prizes array (v2 requirement)`,path:`gates.${d}`});l.length>0&&r.push({file:c,valid:l.every(d=>d.type!=="error"),issues:l});}let i=r.reduce((a,c)=>a+c.issues.length,0),o=r.every(a=>a.valid);return z({action:"validate",valid:o,totalFiles:r.length,totalIssues:i,results:r})}var ro=[{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}],Wc=30*1e3,Wn=new Map;function Y(t){let e=$.resolve(t),s=Wn.get(e);if(s&&Date.now()-s.loadedAt<Wc)return s.habits;let n=zc(e);return Wn.set(e,{habits:n,loadedAt:Date.now()}),n}function zc(t){let e=new Map;for(let a of ro)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",n=Ki($.join(s,".paradigm","habits.yaml"));n&&Xi(e,n);let r=Qi($.join(s,".paradigm","habits"));for(let a of r)e.set(a.id,a);let i=Ki($.join(t,".paradigm","habits.yaml"));i&&Xi(e,i);let o=Qi($.join(t,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function Ki(t){if(!I.existsSync(t))return null;try{let e=I.readFileSync(t,"utf8");return qe.load(e)}catch{return null}}function Xi(t,e){if(e.habits)for(let s of e.habits)t.set(s.id,{...s});if(e.overrides)for(let[s,n]of Object.entries(e.overrides)){let r=t.get(s);r&&(n.severity!==void 0&&(r.severity=n.severity),n.enabled!==void 0&&(r.enabled=n.enabled));}}function Bc(t,e){return t.filter(s=>s.enabled&&s.trigger===e)}function zn(t){Wn.delete($.resolve(t));}function Qi(t){if(!I.existsSync(t))return [];try{let e=I.readdirSync(t).filter(n=>n.endsWith(".habit")).sort(),s=[];for(let n of e)try{let r=I.readFileSync($.join(t,n),"utf8"),i=qe.load(r);i?.id&&i?.name&&s.push(i);}catch{}return s}catch{return []}}var Zi=["discovery","verification","testing","documentation","collaboration","security"],eo=["preflight","postflight","on-commit","on-stop"],to=["advisory","warn","block"],no=["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"],Vc=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Bn(t){let e=[];if(t.id||e.push("Missing required field: id"),t.name||e.push("Missing required field: name"),t.description||e.push("Missing required field: description"),t.category||e.push("Missing required field: category"),t.trigger||e.push("Missing required field: trigger"),t.severity||e.push("Missing required field: severity"),t.check||e.push("Missing required field: check"),(t.enabled===void 0||t.enabled===null)&&e.push("Missing required field: enabled"),t.id&&!Vc.test(t.id)&&e.push(`Invalid id format: "${t.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),t.category&&!Zi.includes(t.category)&&e.push(`Invalid category: "${t.category}" \u2014 must be one of: ${Zi.join(", ")}`),t.trigger&&!eo.includes(t.trigger)&&e.push(`Invalid trigger: "${t.trigger}" \u2014 must be one of: ${eo.join(", ")}`),t.severity&&!to.includes(t.severity)&&e.push(`Invalid severity: "${t.severity}" \u2014 must be one of: ${to.join(", ")}`),t.check){no.includes(t.check.type)||e.push(`Invalid check.type: "${t.check.type}" \u2014 must be one of: ${no.join(", ")}`);let s=t.check.params||{};switch(t.check.type){case "tool-called":(!s.tools||!Array.isArray(s.tools)||s.tools.length===0)&&e.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!s.patterns||!Array.isArray(s.patterns)||s.patterns.length===0)&&e.push(`check.type "${t.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!s.messagePatterns||!Array.isArray(s.messagePatterns)||s.messagePatterns.length===0)&&e.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:e.length===0,errors:e}}var Yc=new Set(ro.map(t=>t.id));function zt(t){return Yc.has(t)}function Vn(t,e,s="project"){let n=s==="global"?$.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):$.join(t,".paradigm","habits");I.existsSync(n)||I.mkdirSync(n,{recursive:true});let r=$.join(n,`${e.id}.habit`),i=qe.dump(e,{lineWidth:120,noRefs:true});return I.writeFileSync(r,i,"utf8"),zn(t),r}function so(t,e){if(zt(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=$.join(t,".paradigm","habits",`${e}.habit`);if(I.existsSync(s))return I.unlinkSync(s),zn(t),{removed:true};let n=process.env.HOME||process.env.USERPROFILE||"~",r=$.join(n,".paradigm","habits",`${e}.habit`);return I.existsSync(r)?(I.unlinkSync(r),zn(t),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var Yn=0;function gt(t,e,s,n,r){let i=Bc(t,e);n&&(i=i.filter(p=>!p.platforms||p.platforms.includes(n)));let o=0;if(r)try{let{isGraduated:p}=(Wt(),d$a(Yi)),g=i.length;i=i.filter(m=>!p(r,m.id)),o=g-i.length;}catch{}Yn=o;let a=i.map(p=>Kc(p,s)),c=a.filter(p=>p.result==="followed").length,l=a.filter(p=>p.result==="skipped").length,d=a.filter(p=>p.result==="partial").length,u=a.filter(p=>p.result==="skipped"&&p.habit.severity==="block").length;return {trigger:e,evaluations:a,summary:{total:a.length,followed:c,skipped:l,partial:d,blockingViolations:u},blocksCompletion:u>0}}function ft(t){return {toolsCalled:t.toolsCalled||[],filesModified:t.filesModified||[],symbolsTouched:t.symbolsTouched||[],loreRecorded:t.loreRecorded||false,hasPortalRoutes:t.hasPortalRoutes||false,taskAddsRoutes:t.taskAddsRoutes||false,taskDescription:t.taskDescription,gitClean:t.gitClean}}function Kc(t,e){switch(t.check.type){case "tool-called":return Xc(t,e);case "file-exists":return Qc(t,e);case "file-modified":return rl(t,e);case "lore-recorded":return Zc(t,e);case "symbols-registered":return el(t,e);case "gates-declared":return tl(t,e);case "tests-exist":return nl(t,e);case "git-clean":return sl(t,e);case "commit-message-format":return il(t,e);case "flow-coverage":return ol(t,e);case "context-checked":return al(t,e);case "aspect-anchored":return cl(t,e);default:return {habit:t,result:"partial",reason:`Unknown check: ${t.check.type}`}}}function Xc(t,e){let s=t.check.params.tools||[];if(s.length===0)return {habit:t,result:"followed",reason:"No tools required"};let n=s.filter(r=>e.toolsCalled.includes(r));return n.length>0?{habit:t,result:"followed",reason:`Called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, habit not applicable"}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function Qc(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};if(e.filesModified.some(r=>r.endsWith(".purpose")||r.includes(".paradigm/")))return {habit:t,result:"followed",reason:"Purpose files updated"};let n=e.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 n.length===0?{habit:t,result:"followed",reason:"Only non-source files modified"}:{habit:t,result:"skipped",reason:`${n.length} source file(s) without .purpose updates`,evidence:n.slice(0,5)}}function Zc(t,e){let s=e.filesModified.filter(n=>!n.endsWith(".md")&&!n.endsWith(".json")&&!n.endsWith(".yaml")&&!n.endsWith(".yml")&&!n.endsWith(".lock")&&!n.endsWith(".purpose")&&!n.includes(".paradigm/"));return s.length<3?{habit:t,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:t,result:"followed",reason:"Lore recorded"}:{habit:t,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function el(t,e){if(e.symbolsTouched.length===0)return {habit:t,result:"followed",reason:"No symbols touched"};let n=["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=>e.toolsCalled.includes(r));return n.length>0?{habit:t,result:"followed",reason:`Purpose tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function tl(t,e){if(!e.taskAddsRoutes)return {habit:t,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:t,result:"followed",reason:"Portal.yaml has routes"};let n=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(r=>e.toolsCalled.includes(r));return n.length>0?{habit:t,result:"followed",reason:`Gate tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:"Routes added without gate declarations"}}function nl(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=e.filesModified.filter(r=>r.includes(".test.")||r.includes(".spec.")||r.includes("/tests/")||r.includes("/test/")||r.includes("__tests__"));if(s.length>0)return {habit:t,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let n=e.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 n.length===0?{habit:t,result:"followed",reason:"No source files to test"}:{habit:t,result:"partial",reason:`${n.length} source file(s), no test files updated`,evidence:n.slice(0,5)}}function rl(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=t.check.params.patterns||[];if(s.length===0)return {habit:t,result:"followed",reason:"No patterns specified"};if(t.trigger==="on-stop"&&t.severity==="block"){let r=e.filesModified.filter(i=>s.some(o=>i.includes(o)||$.basename(i)===o));return r.length>0?{habit:t,result:"followed",reason:`Matching files: ${r.join(", ")}`,evidence:r}:{habit:t,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let n=e.filesModified.filter(r=>s.some(i=>r.includes(i)||$.basename(r)===i));return n.length>0?{habit:t,result:"followed",reason:`Matching files: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function sl(t,e){return e.filesModified.length===0?{habit:t,result:"followed",reason:"No files modified"}:t.trigger==="on-stop"?{habit:t,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:t,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:t,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:t,result:"skipped",reason:"Uncommitted changes in working tree"}}function il(t,e){if(!e.commitMessage)return {habit:t,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=t.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],n=s.filter(r=>new RegExp(r,"m").test(e.commitMessage));if(n.length===s.length)return {habit:t,result:"followed",reason:"Commit message matches all required patterns",evidence:n};if(n.length>0){let r=s.filter(i=>!new RegExp(i,"m").test(e.commitMessage));return {habit:t,result:"partial",reason:`Matches ${n.length}/${s.length} patterns. Missing: ${r.join(", ")}`}}return {habit:t,result:"skipped",reason:"Commit message does not match required format patterns"}}function ol(t,e){let s=e.symbolsTouched.filter(i=>i.startsWith("#"));if(s.length<3)return {habit:t,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:t,result:"followed",reason:"Flow coverage exists for multi-component changes"};let r=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(i=>e.toolsCalled.includes(i));return r.length>0?{habit:t,result:"followed",reason:`Flow tools called: ${r.join(", ")}`,evidence:r}:{habit:t,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function al(t,e){let n=(t.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(r=>e.toolsCalled.includes(r));return n.length>0?{habit:t,result:"followed",reason:`Context tools called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, context check not applicable"}:{habit:t,result:"skipped",reason:"No context/session tools called during session"}}function cl(t,e){let s=e.symbolsTouched.filter(n=>n.startsWith("~"));return s.length===0?{habit:t,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:t,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:t,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:t,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var ll={"missing-purpose":t=>`${t.target?`"${t.target}"`:"a directory"} is missing a .purpose file. Without it, agents cannot discover what this directory contains or which components live here. The stop hook will block if source files were modified in a directory with no .purpose. Fix: run paradigm_purpose_init for this directory, then add components with paradigm_purpose_add_component.`,"stale-purpose":t=>{let e=t.target?`"${t.target}"`:"a .purpose file",s=t.context?.ageHours!=null?` (${t.context.ageHours}h old)`:"";return `The .purpose file at ${e}${s} has not been updated since the last code change in its directory. Stale purposes mislead agents about what components exist, causing incorrect context injection. Fix: update the .purpose to reflect any added, removed, or changed components, then run paradigm_reindex.`},"missing-gate":t=>`${t.target?`"${t.target}"`:"a route or endpoint"} appears to require authentication or authorization but has no gate declared in portal.yaml. Gates are how Paradigm tracks security enforcement \u2014 missing gates mean agents cannot verify that the route is protected. Fix: add the gate to portal.yaml using paradigm_portal_add_route or paradigm_purpose_add_component with the appropriate gates array.`,"orphan-signal":t=>`${t.target?`"${t.target}"`:"a signal"} is emitted in code but not declared in any .purpose file. Undeclared signals cannot be traced by agents during ripple analysis, meaning downstream effects may be missed when the signal's emitter changes. Fix: add the signal to the nearest .purpose file under its component's signals array (e.g., signals: ["!${t.target||"event-name"}"]). `,"undocumented-flow":t=>`${t.target?`"${t.target}"`:"a multi-step flow"} spans multiple components but has no $flow declaration. Flows with 3 or more steps should be documented so agents can reason about the sequence end-to-end. Without a flow record, agents may implement duplicate logic or miss ordering constraints. Fix: add a flow entry to .paradigm/flows.yaml with the steps and participants.`,"aspect-drift":t=>`${t.target?`"${t.target}"`:"an aspect anchor"} has drifted \u2014 the code at the anchored location no longer matches the fingerprint recorded when the aspect was first applied. This means the aspect may no longer be enforced correctly at that site. Drift is common after refactors that move or rewrite anchored code. Fix: re-anchor the aspect at its new location using paradigm_aspect_anchor, then delete the stale anchor.`,"portal-mismatch":t=>`${t.target?`"${t.target}"`:"a portal.yaml entry"} has a mismatch between what portal.yaml declares and what the code enforces. This could mean a gate is declared but never applied in middleware, or code enforces a check that is not tracked in portal.yaml. Both directions create audit gaps. Fix: reconcile portal.yaml with actual middleware usage \u2014 run paradigm portal check to see specifics.`,"missing-test":t=>`${t.target?`"${t.target}"`:"a component"} has no associated test file. Agents are expected to write tests alongside every implementation. Missing tests increase regression risk and reduce confidence scores for the affected component. Fix: create a test file alongside the implementation (e.g., ${t.target?t.target.replace(/\.[^.]+$/,".test$&"):"component.test.ts"}).`,"uncovered-route":t=>`${t.target?`"${t.target}"`:"a route"} appears in the codebase but is not listed in portal.yaml. All routes \u2014 protected or public \u2014 should be tracked in portal.yaml so the full API surface is visible to agents and reviewers. Uncovered routes are invisible to ripple analysis and gate audits. Fix: add the route to portal.yaml with paradigm_portal_add_route.`,"broken-reference":t=>`${t.target?`"${t.target}"`:"a symbol reference"} references a symbol or file that no longer exists. Broken references in .purpose files cause agents to load stale context and may indicate a renamed or deleted component. Fix: update the reference to the new symbol name, or remove it if the component was deleted. Run paradigm_reindex after fixing to regenerate the scan index.`,"missing-description":t=>`${t.target?`"${t.target}"`:"a component or gate"} has no description. Descriptions are required for agents to understand purpose and context during context injection. Without descriptions, agents may misapply the component or skip it when it would have been relevant. Fix: add a description field to the component or gate entry in its .purpose or portal.yaml file.`,"enforcement-level-violation":t=>{let e=t.target?`"${t.target}"`:"a data category",s=t.context?.ring,n=t.context?.boundary;return `${e} is being transmitted across a boundary (${n||"unknown boundary"}) that exceeds its trust ring${s?` (Ring: ${s})`:""}. Data policy requires project-locked content to never leave the project boundary. This gap could expose internal compliance data externally. Fix: check the data-policy.yaml configuration and ensure the content category is listed in the deny_content for the relevant stream.`},"index-stale":t=>{let e=t.target?`"${t.target}"`:"the scan index",s=t.context?.ageHours,n=s!=null?` (${s} hours old)`:"";return `${e}${n} is stale. The scan index drives context injection, navigator, and ripple analysis. When the index is out of date, agents work from stale symbol maps and may miss recently added components or references. Fix: run paradigm_reindex (or "paradigm index") to regenerate the index.`}};function dl(t,e){let s=ll[t];return s?s({...e,type:t}):`Unknown check type "${t}" \u2014 no narration template available.`}function oo(t){let e=[],s=[],n=[];for(let o of t){let a=dl(o.type,o),c=o.severity??"improvement",l={type:o.type,target:o.target,narration:a,severity:c};c==="blocking"?e.push(l):c==="note"?n.push(l):s.push(l);}let r=e.length+s.length+n.length,i=pl(e,s,n);return {gapCount:r,blocking:e,improvement:s,note:n,narrative:i}}function pl(t,e,s){let n=[],r=t.length+e.length+s.length;if(r===0)return "No gaps found. All enforcement checks passed.";if(n.push(`Found ${r} gap${r!==1?"s":""} across ${io(t,e,s)} check type${io(t,e,s)!==1?"s":""}.`),n.push(""),t.length>0){n.push(`BLOCKING (${t.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let i of t)n.push(`[${i.type}]${i.target?` \u2014 ${i.target}`:""}`),n.push(i.narration),n.push("");}if(e.length>0){n.push(`IMPROVEMENTS (${e.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let i of e)n.push(`[${i.type}]${i.target?` \u2014 ${i.target}`:""}`),n.push(i.narration),n.push("");}if(s.length>0){n.push(`NOTES (${s.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500");for(let i of s)n.push(`[${i.type}]${i.target?` \u2014 ${i.target}`:""}`),n.push(i.narration),n.push("");}return n.join(`
65
65
  `).trimEnd()}function io(t,e,s){let n=new Set;for(let r of [...t,...e,...s])n.add(r.type);return n.size}function Kn(t){if(!t)return [];let e=t.gates;if(e==null)return [];if(Array.isArray(e))return e.map(s=>{if(s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"){let n=s.id;return n.startsWith("^")?n.slice(1):n}return null}).filter(s=>s!==null);if(typeof e=="object")return Object.keys(e).map(s=>s.startsWith("^")?s.slice(1):s);throw new Error(`Invalid gateConfig.gates shape: expected Array or Record, got ${typeof e}`)}var gl=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,fl=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],ml=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function ao(){return [{name:"paradigm_pm_preflight",description:`REQUIRED before implementing features. Call with mode="plan" to get the right agents and cost estimate. Skipping this for complex tasks leads to missed security reviews and wasted tokens.
66
66
 
67
- Runs pre-flight compliance checks: extracts affected symbols, runs ripple analysis, checks portal.yaml status, and suggests required agents. Returns affected symbols, ripple summary, gate recommendations, and suggested agents. ~300 tokens.`,inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze for compliance requirements"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pm_postflight",description:"Run after completing a task to check compliance. Verifies that new components, routes, and events are properly registered in .purpose files and portal.yaml. Flags unregistered symbols and uncaptured wisdom. Returns compliance checklist with pass/fail status for purpose files, portal.yaml, and wisdom capture. ~200 tokens.",inputSchema:{type:"object",properties:{filesModified:{type:"array",items:{type:"string"},description:"List of files modified during the task"},symbolsTouched:{type:"array",items:{type:"string"},description:'List of symbols (e.g., ["#auth-handler", "^authenticated"]) touched during the task'}},required:["filesModified","symbolsTouched"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function co(t,e,s){switch(t){case "paradigm_pm_preflight":{let{task:n}=e,r=await yl(n,s),i=JSON.stringify(r,null,2);return O(i.length,t),{text:i,handled:true}}case "paradigm_pm_postflight":{let{filesModified:n,symbolsTouched:r}=e,i=bl(n,r,s),o=JSON.stringify(i,null,2);return O(o.length,t),{text:o,handled:true}}default:return {text:"",handled:false}}}async function yl(t,e){let s=t.toLowerCase(),n=t.match(gl)||[],r=[...new Set(n)],i=r.map(p=>{let g=m(e.index,p),m$1=g.length>0?g[0]:null;return {symbol:p,exists:!!m$1,type:m$1?.type,description:m$1?.description}}),o=i.filter(p=>p.exists).map(p=>{let g=n$2(e.index,p.symbol),m=new Set;for(let v of g){let h=n$2(e.index,v.symbol);for(let b of h)b.symbol!==p.symbol&&!g.find(w=>w.symbol===b.symbol)&&m.add(b.symbol);}let y=g.length+m.size,f="low";return y>10?f="high":y>3&&(f="medium"),{symbol:p.symbol,directDependents:g.length,indirectDependents:m.size,impact:f}}),a={exists:e.gateConfig!==null,gateCount:0,gates:[],routeCount:0};if(e.gateConfig){let p=Kn(e.gateConfig);a.gateCount=p.length,a.gates=p.map(m=>`^${m}`);let g=e.gateConfig.routes;a.routeCount=g&&!Array.isArray(g)&&typeof g=="object"?Object.keys(g).length:0;}let c=fl.some(p=>s.includes(p)),l=[];i.some(p=>p.exists)&&l.push("ripple-analysis"),c&&l.push("portal-compliance"),r.some(p=>p.startsWith("^"))&&l.push("gate-validation"),r.some(p=>p.startsWith("!"))&&l.push("signal-registration"),l.push("purpose-coverage");let d=null,u=null;try{let p=Y(e.rootDir),m=j().getStats(),y=[...new Set(m.toolCalls.map(b=>b.toolName))],f=ft({toolsCalled:y,filesModified:[],symbolsTouched:r,loreRecorded:!1,hasPortalRoutes:a.exists&&a.routeCount>0,taskAddsRoutes:c,taskDescription:t}),v=gt(p,"preflight",f,void 0,e.rootDir);d={total:v.summary.total,followed:v.summary.followed,skipped:v.summary.skipped,partial:v.summary.partial,results:v.evaluations.map(b=>({id:b.habit.id,name:b.habit.name,severity:b.habit.severity,result:b.result,reason:b.reason}))};let h=new Date(Date.now()-720*60*60*1e3).toISOString();u=await x$2(e.rootDir,{dateFrom:h});}catch{}return {task:t.slice(0,100)+(t.length>100?"...":""),affectedSymbols:i,rippleAnalysis:o,portalStatus:a,taskAddsRoutes:c,requiredChecks:l,recommendations:hl(i,o,a,c),habits:{evaluation:d,recentCompliance:u?{rate:u.rate,totalEvents:u.total}:null}}}function hl(t,e,s,n){let r=[],i=t.filter(c=>!c.exists);i.length>0&&r.push(`New symbols detected: ${i.map(c=>c.symbol).join(", ")}. Register in .purpose files after implementation.`);let o=e.filter(c=>c.impact==="high");o.length>0&&r.push(`HIGH IMPACT: ${o.map(c=>c.symbol).join(", ")} \u2014 review all dependents before modifying.`),n&&!s.exists?r.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):n&&r.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let a=t.filter(c=>c.symbol.startsWith("^")&&!c.exists);return a.length>0&&r.push(`New gates referenced: ${a.map(c=>c.symbol).join(", ")}. Add to portal.yaml.`),r}function bl(t,e,s){let n=[],r=s.gateConfig?.routes,i=r&&!Array.isArray(r)&&typeof r=="object"?Object.keys(r):[];for(let m of t){let y=$.isAbsolute(m)?m:$.join(s.rootDir,m);if(!A.existsSync(y))continue;let f;try{f=A.readFileSync(y,"utf-8");}catch{continue}for(let v of ml){v.lastIndex=0;let h;for(;(h=v.exec(f))!==null;){let b=h[2]||h[0];b&&b.startsWith("/")&&(!i.some(x=>x.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===b)&&s.gateConfig?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${b}" in ${$.relative(s.rootDir,y)} not in portal.yaml`,file:$.relative(s.rootDir,y),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!s.gateConfig&&b.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${b}" found but no portal.yaml exists`,file:$.relative(s.rootDir,y),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let m$1 of e)m(s.index,m$1).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${m$1}" is not registered in any .purpose file`,suggestion:"Add to nearest .purpose file using paradigm_purpose_add_component or paradigm_purpose_add_signal."});let o=Kn(s.gateConfig);for(let m of e)if(m.startsWith("^")){let y=m.slice(1);o.includes(y)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${m}" referenced but not declared in portal.yaml`,suggestion:`Add ${m} to portal.yaml with description and check expression.`});}for(let m of t$3(s.index,e,s.rootDir))n.push({type:"stale-aspect",severity:"warning",message:m.kind==="no-anchors"?`Aspect "${m.aspectSymbol}" has no code anchors`:`Aspect "${m.aspectSymbol}" anchor "${m.anchorRaw}" points to missing file`,suggestion:m.kind==="no-anchors"?`Add anchors to ${m.aspectSymbol} in .purpose file. Run paradigm_aspect_check for details.`:`Update anchors for ${m.aspectSymbol} in .purpose file.`});let a=l(s.index,"aspect");for(let m of a){let y=m.appliesTo||[];if(y.length!==0)for(let f of e){if(!f.startsWith("#"))continue;(m.data||{}).aspects||[];for(let b of y){if(!b.includes("*"))continue;if(new RegExp("^"+b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(f))break}}}t.length>=5&&e.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${t.length} files, ${e.length} symbols) \u2014 consider recording decisions`,suggestion:"Use paradigm_wisdom_record to capture architectural decisions or antipatterns."});for(let m$1 of e){let y=m(s.index,m$1);if(y.length===0)continue;let f=y[0];f.parentSymbol&&m(s.index,f.parentSymbol).length===0&&n.push({type:"broken-reference",severity:"warning",message:`Symbol "${m$1}" references parent "${f.parentSymbol}" which does not exist`,suggestion:"Create the parent symbol or update the parent reference in the .purpose file."});}let c=n.filter(m=>m.severity==="error").length,l$1=n.filter(m=>m.severity==="warning").length,d="pass";c>0?d="violations":l$1>0&&(d="warnings");let u=null;try{let m=Y(s.rootDir),f=j().getStats(),v=[...new Set(f.toolCalls.map(_=>_.toolName))],h=v.includes("paradigm_lore_record"),b;try{b=execSync("git status --porcelain",{cwd:s.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let w=ft({toolsCalled:v,filesModified:t,symbolsTouched:e,loreRecorded:h,hasPortalRoutes:s.gateConfig!==null&&s.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:b}),x=gt(m,"postflight",w,void 0,s.rootDir);u={trigger:"postflight",total:x.summary.total,followed:x.summary.followed,skipped:x.summary.skipped,partial:x.summary.partial,blockingViolations:x.summary.blockingViolations,results:x.evaluations.map(_=>({id:_.habit.id,name:_.habit.name,severity:_.habit.severity,result:_.result,reason:_.reason}))};let k=$.join(s.rootDir,".paradigm",".habits-blocking");if(x.blocksCompletion){let _=x.evaluations.filter(T=>T.result==="skipped"&&T.habit.severity==="block").map(T=>`${T.habit.name}: ${T.reason}`);A.writeFileSync(k,_.join(`
68
- `),"utf8");}else A.existsSync(k)&&A.unlinkSync(k);}catch{}let p=n.map(m=>({type:{"missing-purpose":"missing-purpose","missing-portal-gate":"missing-gate","unregistered-symbol":"missing-purpose","uncaptured-wisdom":"missing-description","stale-aspect":"aspect-drift","broken-reference":"broken-reference"}[m.type]??"missing-description",target:m.file||m.message.slice(0,80),severity:m.severity==="error"?"blocking":"improvement"})),g=p.length>0?oo(p):null;return {status:d,violations:n,summary:{totalChecks:7,passed:7-(c>0?1:0)-(l$1>0?1:0),warnings:l$1,errors:c},blocksCompletion:c>0,habitsEvaluation:u,...g?{narrations:g}:{}}}function po(){return [{name:"paradigm_habits_list",description:"List all habit definitions: seed (built-in), global (~/.paradigm/habits.yaml), and project (.paradigm/habits.yaml). Shows what habits exist, their triggers, severity, and enabled state. Use to discover available habits before evaluating them. Returns habit definitions with id, check type, trigger, severity, category, and enabled state. ~300 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"Filter by trigger point"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Filter by category"},enabled:{type:"boolean",description:"Filter by enabled state (default: show all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_check",description:"Evaluate habit compliance for the current session and record practice events. Call at preflight (before implementing), postflight (after implementing), or on-stop (session end). Returns which habits were followed, skipped, or partially met. Returns per-habit follow/skip/partial results and blocking status. ~200 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-stop","on-commit"],description:"When to evaluate: preflight (before task), postflight (after task), on-stop (session end)"},filesModified:{type:"array",items:{type:"string"},description:"Files modified during the session/task"},symbolsTouched:{type:"array",items:{type:"string"},description:"Symbols touched during the session/task"},taskDescription:{type:"string",description:"Description of the task being performed"},record:{type:"boolean",description:"Whether to record practice events (default: true)"}},required:["trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_status",description:"View practice profile: compliance rates by category, trends, and incident correlations. Shows how well habits are being followed over time. Returns overall rate, per-category rates, trend direction, and incident correlations. ~200 tokens.",inputSchema:{type:"object",properties:{engineer:{type:"string",description:"Filter by engineer name (default: all)"},period:{type:"string",enum:["7d","30d","90d","all"],description:"Time period for analysis (default: 30d)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_practice_context",description:"Get proactive practice warnings before modifying symbols. Shows recent compliance gaps and team-aware suggestions. Call this alongside paradigm_wisdom_context for full context. Returns relevant habits, compliance gaps, and behavioral suggestions. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols about to be modified"},task:{type:"string",description:"Description of the upcoming task"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_add",description:'Create a new custom habit as an individual .habit file. Validates all fields and checks for ID collisions with seed habits. Use scope "global" for ~/.paradigm/habits/ or "project" (default) for .paradigm/habits/. ~150 tokens.',inputSchema:{type:"object",properties:{id:{type:"string",description:'Unique habit ID in kebab-case (e.g. "check-changelog")'},name:{type:"string",description:"Human-readable habit name"},description:{type:"string",description:"What this habit checks and why"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Habit category"},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"When the habit is evaluated"},severity:{type:"string",enum:["advisory","warn","block"],description:"How strictly to enforce (block prevents session completion)"},check:{type:"object",description:"Check definition with type and params",properties:{type:{type:"string",enum:["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"]},params:{type:"object",description:"Check-specific parameters (tools[], patterns[], etc.)"}},required:["type","params"]},enabled:{type:"boolean",description:"Whether the habit is active (default: true)"},platforms:{type:"array",items:{type:"string"},description:'Platforms this habit applies to (e.g. ["claude", "cursor"]). Omit for all.'},scope:{type:"string",enum:["project","global"],description:'Where to save: "project" (default) or "global" (~/.paradigm/habits/)'}},required:["id","name","description","category","trigger","severity","check"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_edit",description:"Update fields on an existing custom .habit file. Cannot edit seed habits \u2014 use overrides in habits.yaml instead. Merges provided fields with existing definition and re-validates. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to edit"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"]},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"]},severity:{type:"string",enum:["advisory","warn","block"]},check:{type:"object",properties:{type:{type:"string"},params:{type:"object"}},required:["type","params"]},enabled:{type:"boolean"},platforms:{type:"array",items:{type:"string"}}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_remove",description:"Delete a custom .habit file. Cannot remove seed habits \u2014 use overrides to disable them instead. Searches both project and global habit directories. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to remove"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function uo(t,e,s){switch(t){case "paradigm_habits_list":{let n=wl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_check":{let n=await kl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_status":{let n=await Rl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_practice_context":{let n=await Pl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_add":{let n=Sl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_edit":{let n=xl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_remove":{let n=Cl(e,s);return O(n.length,t),{text:n,handled:true}}default:return {text:"",handled:false}}}function wl(t,e){let s=t.trigger,n=t.category,r=t.enabled,i=Y(e.rootDir);s&&(i=i.filter(a=>a.trigger===s)),n&&(i=i.filter(a=>a.category===n)),r!==void 0&&(i=i.filter(a=>a.enabled===r));let o={};for(let a of i)o[a.trigger]||(o[a.trigger]=[]),o[a.trigger].push(a);return JSON.stringify({total:i.length,filters:Object.fromEntries(Object.entries({trigger:s,category:n,enabled:r}).filter(([,a])=>a!==void 0)),byTrigger:Object.fromEntries(Object.entries(o).map(([a,c])=>[a,c.map(l=>({id:l.id,name:l.name,description:l.description,category:l.category,severity:l.severity,enabled:l.enabled,check:{type:l.check.type,params:l.check.params},platforms:l.platforms||null}))]))},null,2)}async function kl(t,e){let s=t.trigger,n=t.filesModified||[],r=t.symbolsTouched||[],i=t.taskDescription,o=t.record!==false,a=Y(e.rootDir),c=j(),l=c.getStats(),d=[...new Set(l.toolCalls.map(x=>x.toolName))],u=d.includes("paradigm_lore_record"),p=(i||"").toLowerCase(),g=["endpoint","route","api","handler","get","post","put","patch","delete"].some(x=>p.includes(x)),m;try{m=execSync("git status --porcelain",{cwd:e.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let y=ft({toolsCalled:d,filesModified:n,symbolsTouched:r,loreRecorded:u,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:g,taskDescription:i,gitClean:m}),v=gt(a,s,y,"claude",e.rootDir),h=[];if(o&&v.evaluations.length>0)try{let x=c.getLastLoreEntryId()??void 0;h=await z$5(e.rootDir,v.evaluations.map(k=>({habitId:k.habit.id,habitCategory:k.habit.category,result:k.result,notes:k.reason})),{engineer:"agent",sessionId:l.sessionId,loreEntryId:x,taskDescription:i,symbolsTouched:r,filesModified:n});}catch{}let b=$.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&v.blocksCompletion){let x=v.evaluations.filter(k=>k.result==="skipped"&&k.habit.severity==="block").map(k=>`${k.habit.name}: ${k.reason}`);A.writeFileSync(b,x.join(`
69
- `),"utf8");}else s==="on-stop"&&A.existsSync(b)&&A.unlinkSync(b);}catch{}let w=Yn;return JSON.stringify({trigger:s,evaluation:{total:v.summary.total,followed:v.summary.followed,skipped:v.summary.skipped,partial:v.summary.partial,blockingViolations:v.summary.blockingViolations,blocksCompletion:v.blocksCompletion},...w>0?{graduatedToHooks:w,graduatedNote:`${w} habit(s) enforced by hooks (zero context cost). Not re-evaluated here.`}:{},habits:v.evaluations.map(x=>({id:x.habit.id,name:x.habit.name,category:x.habit.category,severity:x.habit.severity,result:x.result,reason:x.reason,evidence:x.evidence})),recorded:o?h.length:0,recommendations:_l(v)},null,2)}function _l(t){let e=[];for(let s of t.evaluations)if(s.result==="skipped")switch(s.habit.id){case "explore-before-implement":case "ripple-before-modify":e.push("Call paradigm_ripple or paradigm_navigate before modifying symbols.");break;case "check-fragility":e.push("Call paradigm_history_fragility to check for fragile symbols.");break;case "wisdom-before-implement":e.push("Call paradigm_wisdom_context to check team preferences and antipatterns.");break;case "verify-before-done":e.push("Call paradigm_pm_postflight to verify compliance before finishing.");break;case "record-lore-for-significant":e.push("Call paradigm_lore_record to document this session.");break;case "gates-for-routes":e.push("Call paradigm_gates_for_route and update portal.yaml for new routes.");break;case "purpose-coverage":e.push("Update .purpose files using paradigm_purpose_add_component.");break;case "changelog-updated":e.push("Update CHANGELOG.md with the changes made in this phase.");break;case "changes-committed":e.push("Commit all changes to git before finishing this phase.");break;default:e.push(`${s.habit.name}: ${s.reason}`);}return [...new Set(e)]}function Sl(t,e){let s=t.id,n=t.scope||"project";if(zt(s))return JSON.stringify({error:true,message:`Cannot create habit "${s}" \u2014 it collides with a seed habit. Choose a different ID or use overrides in habits.yaml to customize the seed habit.`},null,2);if(Y(e.rootDir).find(l=>l.id===s))return JSON.stringify({error:true,message:`Habit "${s}" already exists. Use paradigm_habits_edit to update it, or choose a different ID.`},null,2);let o={id:s,name:t.name,description:t.description,category:t.category,trigger:t.trigger,severity:t.severity,check:t.check,enabled:t.enabled!==void 0?t.enabled:true};t.platforms&&(o.platforms=t.platforms);let a=Bn(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=Vn(e.rootDir,o,n);return JSON.stringify({created:true,id:o.id,filePath:c,scope:n,message:`Habit "${o.name}" created at ${c}`},null,2)}function xl(t,e){let s=t.id;if(zt(s))return JSON.stringify({error:true,message:`Cannot edit "${s}" \u2014 it is a seed habit. To customize it, add an override in .paradigm/habits.yaml under the "overrides:" key.`},null,2);let n=$.join(e.rootDir,".paradigm","habits",`${s}.habit`),r=process.env.HOME||process.env.USERPROFILE||"~",i=$.join(r,".paradigm","habits",`${s}.habit`),o=null,a="project";if(A.existsSync(n)?(o=n,a="project"):A.existsSync(i)&&(o=i,a="global"),!o)return JSON.stringify({error:true,message:`No .habit file found for "${s}". It may be defined in habits.yaml \u2014 edit that file directly.`},null,2);let c;try{let u=A.readFileSync(o,"utf8");c=qe.load(u);}catch{return JSON.stringify({error:true,message:`Failed to read ${o}`},null,2)}let l={...c};t.name!==void 0&&(l.name=t.name),t.description!==void 0&&(l.description=t.description),t.category!==void 0&&(l.category=t.category),t.trigger!==void 0&&(l.trigger=t.trigger),t.severity!==void 0&&(l.severity=t.severity),t.check!==void 0&&(l.check=t.check),t.enabled!==void 0&&(l.enabled=t.enabled),t.platforms!==void 0&&(l.platforms=t.platforms);let d=Bn(l);return d.valid?(Vn(e.rootDir,l,a),JSON.stringify({updated:true,id:l.id,filePath:o,message:`Habit "${l.name}" updated`},null,2)):JSON.stringify({error:true,message:"Validation failed after merge",errors:d.errors},null,2)}function Cl(t,e){let s=t.id,n=so(e.rootDir,s);return n.removed?JSON.stringify({removed:true,id:s,message:`Habit "${s}" removed`},null,2):JSON.stringify({error:true,message:n.reason},null,2)}async function Rl(t,e){let s=t.engineer,n=t.period||"30d",r=new Date,i;if(n!=="all"){let h=parseInt(n.replace("d",""),10)||30;i=new Date(r.getTime()-h*24*60*60*1e3).toISOString();}let o={engineer:s,dateFrom:i},a=await x$2(e.rootDir,o),c=await y$3(e.rootDir,o),l=await w$1(e.rootDir,{...o,limit:200}),d=new Map;for(let h of l){let b=d.get(h.habitId)||{followed:0,skipped:0,partial:0},w=h.result;b[w]++,d.set(h.habitId,b);}let u=null,p=null,g=-1,m=101;for(let h of c)h.rate>g&&(g=h.rate,u=h.category),h.rate<m&&(m=h.rate,p=h.category);let y=Y(e.rootDir),f=new Map(y.map(h=>[h.id,h.name])),v=Array.from(d.entries()).map(([h,b])=>{let w=b.followed+b.skipped+b.partial,x=w>0?Math.round((b.followed+b.partial*.5)/w*100):100;return {habitId:h,habitName:f.get(h)||h,...b,total:w,rate:x}}).sort((h,b)=>h.rate-b.rate);return JSON.stringify({period:n,engineer:s||"all",overall:{totalEvents:a.total,complianceRate:a.rate,followed:a.followed,skipped:a.skipped,partial:a.partial,strongestCategory:u,weakestCategory:p},byCategory:c.map(h=>({category:h.category,rate:h.rate,total:h.total,followed:h.followed,skipped:h.skipped,partial:h.partial})),byHabit:v,activeHabits:y.filter(h=>h.enabled).length,totalHabits:y.length},null,2)}async function Pl(t,e){let s=t.symbols||[],n=t.task,i=Y(e.rootDir).filter(m=>m.enabled&&m.trigger==="preflight"),a=j().getStats(),c=[...new Set(a.toolCalls.map(m=>m.toolName))],l=[];for(let m of i)if(m.check.type==="tool-called"){let y=m.check.params.tools||[];!y.some(v=>c.includes(v))&&s.length>0&&l.push({habitId:m.id,habitName:m.name,category:m.category,severity:m.severity,message:`${m.name}: ${m.description}`,suggestion:`Call one of: ${y.join(", ")}`});}let d=new Date(Date.now()-720*60*60*1e3).toISOString(),u=await x$2(e.rootDir,{dateFrom:d}),g=(await y$3(e.rootDir,{dateFrom:d})).filter(m=>m.rate<60).map(m=>m.category);return JSON.stringify({symbols:s,task:n||null,warnings:l,recentCompliance:{rate:u.rate,totalEvents:u.total,weakAreas:g},preflightReminders:l.length>0?`${l.length} habit(s) not yet followed this session. See warnings above.`:"All preflight habits satisfied."},null,2)}Wt();Gn();async function go(t){let e=Le(t);if(!e.enabled)return [];let s=Y(t),n=[];for(let r of s){if(!r.enabled)continue;let i=await Tl(t,r,e);n.push(i);}return n}async function Tl(t,e,s){let n=Ut(t,e.id),r={habitId:e.id,habitName:e.name,currentTier:n.tier,neverGraduate:false,inCooldown:false};if(n.tier==="hook")return {...r,eligible:false,reason:"Already graduated to hook"};if(n.neverGraduate||s.neverGraduate.includes(e.id))return {...r,eligible:false,reason:"Marked as never-graduate (requires agent cognition)",neverGraduate:true};if(Mn.has(e.check.type))return {...r,eligible:false,reason:`Check type "${e.check.type}" cannot graduate \u2014 requires MCP tool output`,neverGraduate:true};if(n.cooldownUntil&&new Date(n.cooldownUntil)>new Date)return {...r,eligible:false,reason:`In cooldown until ${n.cooldownUntil.split("T")[0]} (demoted recently)`,inCooldown:true};let{thresholds:i}=s,o=new Date;o.setDate(o.getDate()-i.timeWindowDays);try{let a=await x$2(t,{habitId:e.id,dateFrom:o.toISOString()});if(a.total<i.minEvents)return {...r,eligible:!1,reason:`Insufficient data: ${a.total}/${i.minEvents} events in ${i.timeWindowDays}d window`,complianceRate:a.rate,eventCount:a.total};if(a.rate<i.minComplianceRate)return {...r,eligible:!1,reason:`Compliance ${a.rate.toFixed(0)}% < ${i.minComplianceRate}% threshold`,complianceRate:a.rate,eventCount:a.total};let c=new Date;return c.setDate(c.getDate()-i.recencyDays),(await x$2(t,{habitId:e.id,dateFrom:c.toISOString()})).total===0?{...r,eligible:!1,reason:`No events in last ${i.recencyDays} days \u2014 habit may be dormant`,complianceRate:a.rate,eventCount:a.total}:{...r,eligible:!0,reason:`Ready: ${a.rate.toFixed(0)}% compliance over ${a.total} events in ${i.timeWindowDays}d`,complianceRate:a.rate,eventCount:a.total}}catch{return {...r,eligible:false,reason:"Unable to query practice events (Sentinel DB unavailable)"}}}function fo(t){let e=Y(t),s=Le(t),n=Un(t),r=0,i=0,o=0,a=0;for(let c of e){if(!c.enabled)continue;let l=n[c.id],d=l?.tier||"habit",u=l?.neverGraduate||s.neverGraduate.includes(c.id)||Mn.has(c.check.type);d==="hook"?r++:d==="mcp"?o++:i++,u&&a++;}return {hookCount:r,habitCount:i,mcpCount:o,neverGraduateCount:a,states:n}}Wt();var jl=[{name:"paradigm_graduate_check",description:"Check which habits are eligible for graduation from habit tier to hook tier. Returns eligibility status for each habit with compliance data and reasoning. ~300 tokens.",inputSchema:{type:"object",properties:{habitId:{type:"string",description:"Check a specific habit by ID. Omit to check all."}}}},{name:"paradigm_graduate_status",description:"Show the current automation tier of every habit. Returns tier map grouped by hook/habit/mcp with graduation dates and savings estimate. ~200 tokens.",inputSchema:{type:"object",properties:{}}}];async function Ol(t,e){let s=await go(t.rootDir),n=s;if(e.habitId&&(n=s.filter(a=>a.habitId===e.habitId),n.length===0))return JSON.stringify({error:`No habit found with ID "${e.habitId}"`});let r=n.filter(a=>a.eligible),i=n.filter(a=>!a.eligible&&!a.neverGraduate),o=n.filter(a=>a.neverGraduate);return JSON.stringify({summary:{checked:n.length,eligible:r.length,ineligible:i.length,neverGraduate:o.length},...r.length>0?{eligible:r.map(mo),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...i.length>0?{ineligible:i.map(mo)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function Al(t){let e=fo(t.rootDir),s=Le(t.rootDir),n={hook:[],habit:[],mcp:[]};for(let[r,i]of Object.entries(e.states)){let o=i.tier||"habit";n[o]||(n[o]=[]),n[o].push({id:r,...i.graduatedAt?{graduatedAt:i.graduatedAt}:{},...i.neverGraduate?{neverGraduate:true}:{}});}return JSON.stringify({tiers:{hook:e.hookCount,habit:e.habitCount,mcp:e.mcpCount},neverGraduate:e.neverGraduateCount,estimatedSavingsPerSession:`~${e.hookCount*150} tokens`,byTier:n,thresholds:s.thresholds},null,2)}function yo(){return jl}async function ho(t,e,s){switch(t){case "paradigm_graduate_check":return {handled:true,text:await Ol(s,e)};case "paradigm_graduate_status":return {handled:true,text:await Al(s)};default:return {handled:false,text:""}}}function mo(t){return {id:t.habitId,name:t.habitName,tier:t.currentTier,reason:t.reason,...t.complianceRate!==void 0?{complianceRate:t.complianceRate}:{},...t.eventCount!==void 0?{eventCount:t.eventCount}:{},...t.inCooldown?{inCooldown:true}:{}}}var bo=new Set(["the","a","an","is","how","does","what","why","when","where","do","can","will","should","would","could","are","was","were","been","being","have","has","had","this","that","it","its","of","in","to","for","with","on","at","by","from","or","and","but","not"]),Il=.95,Dl=.3,$l=10;function Hl(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let r=Array.from({length:s+1},()=>Array.from({length:n+1},()=>0));for(let i=0;i<=s;i++)r[i][0]=i;for(let i=0;i<=n;i++)r[0][i]=i;for(let i=1;i<=s;i++)for(let o=1;o<=n;o++){let a=t[i-1]===e[o-1]?0:1;r[i][o]=Math.min(r[i-1][o]+1,r[i][o-1]+1,r[i-1][o-1]+a);}return r[s][n]}function vo(t){let e=t.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!bo.has(s));return e.sort(),e.join(" ")}function Fl(t){try{let e=t.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'aspects_fts'");return e.length>0&&e[0].values.length>0}catch{return false}}function wo(t,e,s){let n=s?.limit??$l,r=vo(e);if(r.length===0)return [];let i=Nl(t,r,s);if(i.length>0)return i.slice(0,n);if(Fl(t)){let a=El(t,r,s);if(a.length>0)return a.slice(0,n)}return ql(t,r,s).slice(0,n)}function Nl(t,e,s){try{let n=`
67
+ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analysis, checks portal.yaml status, and suggests required agents. Returns affected symbols, ripple summary, gate recommendations, and suggested agents. ~300 tokens.`,inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze for compliance requirements"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pm_postflight",description:"Run after completing a task to check compliance. Verifies that new components, routes, and events are properly registered in .purpose files and portal.yaml. Flags unregistered symbols and uncaptured wisdom. Returns compliance checklist with pass/fail status for purpose files, portal.yaml, and wisdom capture. ~200 tokens.",inputSchema:{type:"object",properties:{filesModified:{type:"array",items:{type:"string"},description:"List of files modified during the task"},symbolsTouched:{type:"array",items:{type:"string"},description:'List of symbols (e.g., ["#auth-handler", "^authenticated"]) touched during the task'}},required:["filesModified","symbolsTouched"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function co(t,e,s){switch(t){case "paradigm_pm_preflight":{let{task:n}=e,r=await yl(n,s),i=JSON.stringify(r,null,2);return O(i.length,t),{text:i,handled:true}}case "paradigm_pm_postflight":{let{filesModified:n,symbolsTouched:r}=e,i=bl(n,r,s),o=JSON.stringify(i,null,2);return O(o.length,t),{text:o,handled:true}}default:return {text:"",handled:false}}}async function yl(t,e){let s=t.toLowerCase(),n=t.match(gl)||[],r=[...new Set(n)],i=r.map(p=>{let g=m(e.index,p),m$1=g.length>0?g[0]:null;return {symbol:p,exists:!!m$1,type:m$1?.type,description:m$1?.description}}),o=i.filter(p=>p.exists).map(p=>{let g=n$2(e.index,p.symbol),m=new Set;for(let v of g){let h=n$2(e.index,v.symbol);for(let b of h)b.symbol!==p.symbol&&!g.find(w=>w.symbol===b.symbol)&&m.add(b.symbol);}let y=g.length+m.size,f="low";return y>10?f="high":y>3&&(f="medium"),{symbol:p.symbol,directDependents:g.length,indirectDependents:m.size,impact:f}}),a={exists:e.gateConfig!==null,gateCount:0,gates:[],routeCount:0};if(e.gateConfig){let p=Kn(e.gateConfig);a.gateCount=p.length,a.gates=p.map(m=>`^${m}`);let g=e.gateConfig.routes;a.routeCount=g&&!Array.isArray(g)&&typeof g=="object"?Object.keys(g).length:0;}let c=fl.some(p=>s.includes(p)),l=[];i.some(p=>p.exists)&&l.push("ripple-analysis"),c&&l.push("portal-compliance"),r.some(p=>p.startsWith("^"))&&l.push("gate-validation"),r.some(p=>p.startsWith("!"))&&l.push("signal-registration"),l.push("purpose-coverage");let d=null,u=null;try{let p=Y(e.rootDir),m=j$1().getStats(),y=[...new Set(m.toolCalls.map(b=>b.toolName))],f=ft({toolsCalled:y,filesModified:[],symbolsTouched:r,loreRecorded:!1,hasPortalRoutes:a.exists&&a.routeCount>0,taskAddsRoutes:c,taskDescription:t}),v=gt(p,"preflight",f,void 0,e.rootDir);d={total:v.summary.total,followed:v.summary.followed,skipped:v.summary.skipped,partial:v.summary.partial,results:v.evaluations.map(b=>({id:b.habit.id,name:b.habit.name,severity:b.habit.severity,result:b.result,reason:b.reason}))};let h=new Date(Date.now()-720*60*60*1e3).toISOString();u=await x$2(e.rootDir,{dateFrom:h});}catch{}return {task:t.slice(0,100)+(t.length>100?"...":""),affectedSymbols:i,rippleAnalysis:o,portalStatus:a,taskAddsRoutes:c,requiredChecks:l,recommendations:hl(i,o,a,c),habits:{evaluation:d,recentCompliance:u?{rate:u.rate,totalEvents:u.total}:null}}}function hl(t,e,s,n){let r=[],i=t.filter(c=>!c.exists);i.length>0&&r.push(`New symbols detected: ${i.map(c=>c.symbol).join(", ")}. Register in .purpose files after implementation.`);let o=e.filter(c=>c.impact==="high");o.length>0&&r.push(`HIGH IMPACT: ${o.map(c=>c.symbol).join(", ")} \u2014 review all dependents before modifying.`),n&&!s.exists?r.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):n&&r.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let a=t.filter(c=>c.symbol.startsWith("^")&&!c.exists);return a.length>0&&r.push(`New gates referenced: ${a.map(c=>c.symbol).join(", ")}. Add to portal.yaml.`),r}function bl(t,e,s){let n=[],r=s.gateConfig?.routes,i=r&&!Array.isArray(r)&&typeof r=="object"?Object.keys(r):[];for(let m of t){let y=$.isAbsolute(m)?m:$.join(s.rootDir,m);if(!I.existsSync(y))continue;let f;try{f=I.readFileSync(y,"utf-8");}catch{continue}for(let v of ml){v.lastIndex=0;let h;for(;(h=v.exec(f))!==null;){let b=h[2]||h[0];b&&b.startsWith("/")&&(!i.some(x=>x.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===b)&&s.gateConfig?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${b}" in ${$.relative(s.rootDir,y)} not in portal.yaml`,file:$.relative(s.rootDir,y),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!s.gateConfig&&b.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${b}" found but no portal.yaml exists`,file:$.relative(s.rootDir,y),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let m$1 of e)m(s.index,m$1).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${m$1}" is not registered in any .purpose file`,suggestion:"Add to nearest .purpose file using paradigm_purpose_add_component or paradigm_purpose_add_signal."});let o=Kn(s.gateConfig);for(let m of e)if(m.startsWith("^")){let y=m.slice(1);o.includes(y)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${m}" referenced but not declared in portal.yaml`,suggestion:`Add ${m} to portal.yaml with description and check expression.`});}for(let m of t$3(s.index,e,s.rootDir))n.push({type:"stale-aspect",severity:"warning",message:m.kind==="no-anchors"?`Aspect "${m.aspectSymbol}" has no code anchors`:`Aspect "${m.aspectSymbol}" anchor "${m.anchorRaw}" points to missing file`,suggestion:m.kind==="no-anchors"?`Add anchors to ${m.aspectSymbol} in .purpose file. Run paradigm_aspect_check for details.`:`Update anchors for ${m.aspectSymbol} in .purpose file.`});let a=l(s.index,"aspect");for(let m of a){let y=m.appliesTo||[];if(y.length!==0)for(let f of e){if(!f.startsWith("#"))continue;(m.data||{}).aspects||[];for(let b of y){if(!b.includes("*"))continue;if(new RegExp("^"+b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(f))break}}}t.length>=5&&e.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${t.length} files, ${e.length} symbols) \u2014 consider recording decisions`,suggestion:"Use paradigm_wisdom_record to capture architectural decisions or antipatterns."});for(let m$1 of e){let y=m(s.index,m$1);if(y.length===0)continue;let f=y[0];f.parentSymbol&&m(s.index,f.parentSymbol).length===0&&n.push({type:"broken-reference",severity:"warning",message:`Symbol "${m$1}" references parent "${f.parentSymbol}" which does not exist`,suggestion:"Create the parent symbol or update the parent reference in the .purpose file."});}let c=n.filter(m=>m.severity==="error").length,l$1=n.filter(m=>m.severity==="warning").length,d="pass";c>0?d="violations":l$1>0&&(d="warnings");let u=null;try{let m=Y(s.rootDir),f=j$1().getStats(),v=[...new Set(f.toolCalls.map(_=>_.toolName))],h=v.includes("paradigm_lore_record"),b;try{b=execSync("git status --porcelain",{cwd:s.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let w=ft({toolsCalled:v,filesModified:t,symbolsTouched:e,loreRecorded:h,hasPortalRoutes:s.gateConfig!==null&&s.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:b}),x=gt(m,"postflight",w,void 0,s.rootDir);u={trigger:"postflight",total:x.summary.total,followed:x.summary.followed,skipped:x.summary.skipped,partial:x.summary.partial,blockingViolations:x.summary.blockingViolations,results:x.evaluations.map(_=>({id:_.habit.id,name:_.habit.name,severity:_.habit.severity,result:_.result,reason:_.reason}))};let k=$.join(s.rootDir,".paradigm",".habits-blocking");if(x.blocksCompletion){let _=x.evaluations.filter(P=>P.result==="skipped"&&P.habit.severity==="block").map(P=>`${P.habit.name}: ${P.reason}`);I.writeFileSync(k,_.join(`
68
+ `),"utf8");}else I.existsSync(k)&&I.unlinkSync(k);}catch{}let p=n.map(m=>({type:{"missing-purpose":"missing-purpose","missing-portal-gate":"missing-gate","unregistered-symbol":"missing-purpose","uncaptured-wisdom":"missing-description","stale-aspect":"aspect-drift","broken-reference":"broken-reference"}[m.type]??"missing-description",target:m.file||m.message.slice(0,80),severity:m.severity==="error"?"blocking":"improvement"})),g=p.length>0?oo(p):null;return {status:d,violations:n,summary:{totalChecks:7,passed:7-(c>0?1:0)-(l$1>0?1:0),warnings:l$1,errors:c},blocksCompletion:c>0,habitsEvaluation:u,...g?{narrations:g}:{}}}function po(){return [{name:"paradigm_habits_list",description:"List all habit definitions: seed (built-in), global (~/.paradigm/habits.yaml), and project (.paradigm/habits.yaml). Shows what habits exist, their triggers, severity, and enabled state. Use to discover available habits before evaluating them. Returns habit definitions with id, check type, trigger, severity, category, and enabled state. ~300 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"Filter by trigger point"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Filter by category"},enabled:{type:"boolean",description:"Filter by enabled state (default: show all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_check",description:"Evaluate habit compliance for the current session and record practice events. Call at preflight (before implementing), postflight (after implementing), or on-stop (session end). Returns which habits were followed, skipped, or partially met. Returns per-habit follow/skip/partial results and blocking status. ~200 tokens.",inputSchema:{type:"object",properties:{trigger:{type:"string",enum:["preflight","postflight","on-stop","on-commit"],description:"When to evaluate: preflight (before task), postflight (after task), on-stop (session end)"},filesModified:{type:"array",items:{type:"string"},description:"Files modified during the session/task"},symbolsTouched:{type:"array",items:{type:"string"},description:"Symbols touched during the session/task"},taskDescription:{type:"string",description:"Description of the task being performed"},record:{type:"boolean",description:"Whether to record practice events (default: true)"}},required:["trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_status",description:"View practice profile: compliance rates by category, trends, and incident correlations. Shows how well habits are being followed over time. Returns overall rate, per-category rates, trend direction, and incident correlations. ~200 tokens.",inputSchema:{type:"object",properties:{engineer:{type:"string",description:"Filter by engineer name (default: all)"},period:{type:"string",enum:["7d","30d","90d","all"],description:"Time period for analysis (default: 30d)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_practice_context",description:"Get proactive practice warnings before modifying symbols. Shows recent compliance gaps and team-aware suggestions. Call this alongside paradigm_wisdom_context for full context. Returns relevant habits, compliance gaps, and behavioral suggestions. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols about to be modified"},task:{type:"string",description:"Description of the upcoming task"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_habits_add",description:'Create a new custom habit as an individual .habit file. Validates all fields and checks for ID collisions with seed habits. Use scope "global" for ~/.paradigm/habits/ or "project" (default) for .paradigm/habits/. ~150 tokens.',inputSchema:{type:"object",properties:{id:{type:"string",description:'Unique habit ID in kebab-case (e.g. "check-changelog")'},name:{type:"string",description:"Human-readable habit name"},description:{type:"string",description:"What this habit checks and why"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"],description:"Habit category"},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"],description:"When the habit is evaluated"},severity:{type:"string",enum:["advisory","warn","block"],description:"How strictly to enforce (block prevents session completion)"},check:{type:"object",description:"Check definition with type and params",properties:{type:{type:"string",enum:["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"]},params:{type:"object",description:"Check-specific parameters (tools[], patterns[], etc.)"}},required:["type","params"]},enabled:{type:"boolean",description:"Whether the habit is active (default: true)"},platforms:{type:"array",items:{type:"string"},description:'Platforms this habit applies to (e.g. ["claude", "cursor"]). Omit for all.'},scope:{type:"string",enum:["project","global"],description:'Where to save: "project" (default) or "global" (~/.paradigm/habits/)'}},required:["id","name","description","category","trigger","severity","check"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_edit",description:"Update fields on an existing custom .habit file. Cannot edit seed habits \u2014 use overrides in habits.yaml instead. Merges provided fields with existing definition and re-validates. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to edit"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},category:{type:"string",enum:["discovery","verification","testing","documentation","collaboration","security"]},trigger:{type:"string",enum:["preflight","postflight","on-commit","on-stop"]},severity:{type:"string",enum:["advisory","warn","block"]},check:{type:"object",properties:{type:{type:"string"},params:{type:"object"}},required:["type","params"]},enabled:{type:"boolean"},platforms:{type:"array",items:{type:"string"}}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_habits_remove",description:"Delete a custom .habit file. Cannot remove seed habits \u2014 use overrides to disable them instead. Searches both project and global habit directories. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"ID of the habit to remove"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function uo(t,e,s){switch(t){case "paradigm_habits_list":{let n=wl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_check":{let n=await kl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_status":{let n=await Rl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_practice_context":{let n=await Tl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_add":{let n=Sl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_edit":{let n=xl(e,s);return O(n.length,t),{text:n,handled:true}}case "paradigm_habits_remove":{let n=Cl(e,s);return O(n.length,t),{text:n,handled:true}}default:return {text:"",handled:false}}}function wl(t,e){let s=t.trigger,n=t.category,r=t.enabled,i=Y(e.rootDir);s&&(i=i.filter(a=>a.trigger===s)),n&&(i=i.filter(a=>a.category===n)),r!==void 0&&(i=i.filter(a=>a.enabled===r));let o={};for(let a of i)o[a.trigger]||(o[a.trigger]=[]),o[a.trigger].push(a);return JSON.stringify({total:i.length,filters:Object.fromEntries(Object.entries({trigger:s,category:n,enabled:r}).filter(([,a])=>a!==void 0)),byTrigger:Object.fromEntries(Object.entries(o).map(([a,c])=>[a,c.map(l=>({id:l.id,name:l.name,description:l.description,category:l.category,severity:l.severity,enabled:l.enabled,check:{type:l.check.type,params:l.check.params},platforms:l.platforms||null}))]))},null,2)}async function kl(t,e){let s=t.trigger,n=t.filesModified||[],r=t.symbolsTouched||[],i=t.taskDescription,o=t.record!==false,a=Y(e.rootDir),c=j$1(),l=c.getStats(),d=[...new Set(l.toolCalls.map(x=>x.toolName))],u=d.includes("paradigm_lore_record"),p=(i||"").toLowerCase(),g=["endpoint","route","api","handler","get","post","put","patch","delete"].some(x=>p.includes(x)),m;try{m=execSync("git status --porcelain",{cwd:e.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let y=ft({toolsCalled:d,filesModified:n,symbolsTouched:r,loreRecorded:u,hasPortalRoutes:e.gateConfig!==null&&e.gateConfig.routes!=null,taskAddsRoutes:g,taskDescription:i,gitClean:m}),v=gt(a,s,y,"claude",e.rootDir),h=[];if(o&&v.evaluations.length>0)try{let x=c.getLastLoreEntryId()??void 0;h=await z$5(e.rootDir,v.evaluations.map(k=>({habitId:k.habit.id,habitCategory:k.habit.category,result:k.result,notes:k.reason})),{engineer:"agent",sessionId:l.sessionId,loreEntryId:x,taskDescription:i,symbolsTouched:r,filesModified:n});}catch{}let b=$.join(e.rootDir,".paradigm",".habits-blocking");try{if(s==="on-stop"&&v.blocksCompletion){let x=v.evaluations.filter(k=>k.result==="skipped"&&k.habit.severity==="block").map(k=>`${k.habit.name}: ${k.reason}`);I.writeFileSync(b,x.join(`
69
+ `),"utf8");}else s==="on-stop"&&I.existsSync(b)&&I.unlinkSync(b);}catch{}let w=Yn;return JSON.stringify({trigger:s,evaluation:{total:v.summary.total,followed:v.summary.followed,skipped:v.summary.skipped,partial:v.summary.partial,blockingViolations:v.summary.blockingViolations,blocksCompletion:v.blocksCompletion},...w>0?{graduatedToHooks:w,graduatedNote:`${w} habit(s) enforced by hooks (zero context cost). Not re-evaluated here.`}:{},habits:v.evaluations.map(x=>({id:x.habit.id,name:x.habit.name,category:x.habit.category,severity:x.habit.severity,result:x.result,reason:x.reason,evidence:x.evidence})),recorded:o?h.length:0,recommendations:_l(v)},null,2)}function _l(t){let e=[];for(let s of t.evaluations)if(s.result==="skipped")switch(s.habit.id){case "explore-before-implement":case "ripple-before-modify":e.push("Call paradigm_ripple or paradigm_navigate before modifying symbols.");break;case "check-fragility":e.push("Call paradigm_history_fragility to check for fragile symbols.");break;case "wisdom-before-implement":e.push("Call paradigm_wisdom_context to check team preferences and antipatterns.");break;case "verify-before-done":e.push("Call paradigm_pm_postflight to verify compliance before finishing.");break;case "record-lore-for-significant":e.push("Call paradigm_lore_record to document this session.");break;case "gates-for-routes":e.push("Call paradigm_gates_for_route and update portal.yaml for new routes.");break;case "purpose-coverage":e.push("Update .purpose files using paradigm_purpose_add_component.");break;case "changelog-updated":e.push("Update CHANGELOG.md with the changes made in this phase.");break;case "changes-committed":e.push("Commit all changes to git before finishing this phase.");break;default:e.push(`${s.habit.name}: ${s.reason}`);}return [...new Set(e)]}function Sl(t,e){let s=t.id,n=t.scope||"project";if(zt(s))return JSON.stringify({error:true,message:`Cannot create habit "${s}" \u2014 it collides with a seed habit. Choose a different ID or use overrides in habits.yaml to customize the seed habit.`},null,2);if(Y(e.rootDir).find(l=>l.id===s))return JSON.stringify({error:true,message:`Habit "${s}" already exists. Use paradigm_habits_edit to update it, or choose a different ID.`},null,2);let o={id:s,name:t.name,description:t.description,category:t.category,trigger:t.trigger,severity:t.severity,check:t.check,enabled:t.enabled!==void 0?t.enabled:true};t.platforms&&(o.platforms=t.platforms);let a=Bn(o);if(!a.valid)return JSON.stringify({error:true,message:"Validation failed",errors:a.errors},null,2);let c=Vn(e.rootDir,o,n);return JSON.stringify({created:true,id:o.id,filePath:c,scope:n,message:`Habit "${o.name}" created at ${c}`},null,2)}function xl(t,e){let s=t.id;if(zt(s))return JSON.stringify({error:true,message:`Cannot edit "${s}" \u2014 it is a seed habit. To customize it, add an override in .paradigm/habits.yaml under the "overrides:" key.`},null,2);let n=$.join(e.rootDir,".paradigm","habits",`${s}.habit`),r=process.env.HOME||process.env.USERPROFILE||"~",i=$.join(r,".paradigm","habits",`${s}.habit`),o=null,a="project";if(I.existsSync(n)?(o=n,a="project"):I.existsSync(i)&&(o=i,a="global"),!o)return JSON.stringify({error:true,message:`No .habit file found for "${s}". It may be defined in habits.yaml \u2014 edit that file directly.`},null,2);let c;try{let u=I.readFileSync(o,"utf8");c=qe.load(u);}catch{return JSON.stringify({error:true,message:`Failed to read ${o}`},null,2)}let l={...c};t.name!==void 0&&(l.name=t.name),t.description!==void 0&&(l.description=t.description),t.category!==void 0&&(l.category=t.category),t.trigger!==void 0&&(l.trigger=t.trigger),t.severity!==void 0&&(l.severity=t.severity),t.check!==void 0&&(l.check=t.check),t.enabled!==void 0&&(l.enabled=t.enabled),t.platforms!==void 0&&(l.platforms=t.platforms);let d=Bn(l);return d.valid?(Vn(e.rootDir,l,a),JSON.stringify({updated:true,id:l.id,filePath:o,message:`Habit "${l.name}" updated`},null,2)):JSON.stringify({error:true,message:"Validation failed after merge",errors:d.errors},null,2)}function Cl(t,e){let s=t.id,n=so(e.rootDir,s);return n.removed?JSON.stringify({removed:true,id:s,message:`Habit "${s}" removed`},null,2):JSON.stringify({error:true,message:n.reason},null,2)}async function Rl(t,e){let s=t.engineer,n=t.period||"30d",r=new Date,i;if(n!=="all"){let h=parseInt(n.replace("d",""),10)||30;i=new Date(r.getTime()-h*24*60*60*1e3).toISOString();}let o={engineer:s,dateFrom:i},a=await x$2(e.rootDir,o),c=await y$3(e.rootDir,o),l=await w$1(e.rootDir,{...o,limit:200}),d=new Map;for(let h of l){let b=d.get(h.habitId)||{followed:0,skipped:0,partial:0},w=h.result;b[w]++,d.set(h.habitId,b);}let u=null,p=null,g=-1,m=101;for(let h of c)h.rate>g&&(g=h.rate,u=h.category),h.rate<m&&(m=h.rate,p=h.category);let y=Y(e.rootDir),f=new Map(y.map(h=>[h.id,h.name])),v=Array.from(d.entries()).map(([h,b])=>{let w=b.followed+b.skipped+b.partial,x=w>0?Math.round((b.followed+b.partial*.5)/w*100):100;return {habitId:h,habitName:f.get(h)||h,...b,total:w,rate:x}}).sort((h,b)=>h.rate-b.rate);return JSON.stringify({period:n,engineer:s||"all",overall:{totalEvents:a.total,complianceRate:a.rate,followed:a.followed,skipped:a.skipped,partial:a.partial,strongestCategory:u,weakestCategory:p},byCategory:c.map(h=>({category:h.category,rate:h.rate,total:h.total,followed:h.followed,skipped:h.skipped,partial:h.partial})),byHabit:v,activeHabits:y.filter(h=>h.enabled).length,totalHabits:y.length},null,2)}async function Tl(t,e){let s=t.symbols||[],n=t.task,i=Y(e.rootDir).filter(m=>m.enabled&&m.trigger==="preflight"),a=j$1().getStats(),c=[...new Set(a.toolCalls.map(m=>m.toolName))],l=[];for(let m of i)if(m.check.type==="tool-called"){let y=m.check.params.tools||[];!y.some(v=>c.includes(v))&&s.length>0&&l.push({habitId:m.id,habitName:m.name,category:m.category,severity:m.severity,message:`${m.name}: ${m.description}`,suggestion:`Call one of: ${y.join(", ")}`});}let d=new Date(Date.now()-720*60*60*1e3).toISOString(),u=await x$2(e.rootDir,{dateFrom:d}),g=(await y$3(e.rootDir,{dateFrom:d})).filter(m=>m.rate<60).map(m=>m.category);return JSON.stringify({symbols:s,task:n||null,warnings:l,recentCompliance:{rate:u.rate,totalEvents:u.total,weakAreas:g},preflightReminders:l.length>0?`${l.length} habit(s) not yet followed this session. See warnings above.`:"All preflight habits satisfied."},null,2)}Wt();Gn();async function go(t){let e=Le(t);if(!e.enabled)return [];let s=Y(t),n=[];for(let r of s){if(!r.enabled)continue;let i=await Pl(t,r,e);n.push(i);}return n}async function Pl(t,e,s){let n=Ut(t,e.id),r={habitId:e.id,habitName:e.name,currentTier:n.tier,neverGraduate:false,inCooldown:false};if(n.tier==="hook")return {...r,eligible:false,reason:"Already graduated to hook"};if(n.neverGraduate||s.neverGraduate.includes(e.id))return {...r,eligible:false,reason:"Marked as never-graduate (requires agent cognition)",neverGraduate:true};if(Mn.has(e.check.type))return {...r,eligible:false,reason:`Check type "${e.check.type}" cannot graduate \u2014 requires MCP tool output`,neverGraduate:true};if(n.cooldownUntil&&new Date(n.cooldownUntil)>new Date)return {...r,eligible:false,reason:`In cooldown until ${n.cooldownUntil.split("T")[0]} (demoted recently)`,inCooldown:true};let{thresholds:i}=s,o=new Date;o.setDate(o.getDate()-i.timeWindowDays);try{let a=await x$2(t,{habitId:e.id,dateFrom:o.toISOString()});if(a.total<i.minEvents)return {...r,eligible:!1,reason:`Insufficient data: ${a.total}/${i.minEvents} events in ${i.timeWindowDays}d window`,complianceRate:a.rate,eventCount:a.total};if(a.rate<i.minComplianceRate)return {...r,eligible:!1,reason:`Compliance ${a.rate.toFixed(0)}% < ${i.minComplianceRate}% threshold`,complianceRate:a.rate,eventCount:a.total};let c=new Date;return c.setDate(c.getDate()-i.recencyDays),(await x$2(t,{habitId:e.id,dateFrom:c.toISOString()})).total===0?{...r,eligible:!1,reason:`No events in last ${i.recencyDays} days \u2014 habit may be dormant`,complianceRate:a.rate,eventCount:a.total}:{...r,eligible:!0,reason:`Ready: ${a.rate.toFixed(0)}% compliance over ${a.total} events in ${i.timeWindowDays}d`,complianceRate:a.rate,eventCount:a.total}}catch{return {...r,eligible:false,reason:"Unable to query practice events (Sentinel DB unavailable)"}}}function fo(t){let e=Y(t),s=Le(t),n=Un(t),r=0,i=0,o=0,a=0;for(let c of e){if(!c.enabled)continue;let l=n[c.id],d=l?.tier||"habit",u=l?.neverGraduate||s.neverGraduate.includes(c.id)||Mn.has(c.check.type);d==="hook"?r++:d==="mcp"?o++:i++,u&&a++;}return {hookCount:r,habitCount:i,mcpCount:o,neverGraduateCount:a,states:n}}Wt();var jl=[{name:"paradigm_graduate_check",description:"Check which habits are eligible for graduation from habit tier to hook tier. Returns eligibility status for each habit with compliance data and reasoning. ~300 tokens.",inputSchema:{type:"object",properties:{habitId:{type:"string",description:"Check a specific habit by ID. Omit to check all."}}}},{name:"paradigm_graduate_status",description:"Show the current automation tier of every habit. Returns tier map grouped by hook/habit/mcp with graduation dates and savings estimate. ~200 tokens.",inputSchema:{type:"object",properties:{}}}];async function Ol(t,e){let s=await go(t.rootDir),n=s;if(e.habitId&&(n=s.filter(a=>a.habitId===e.habitId),n.length===0))return JSON.stringify({error:`No habit found with ID "${e.habitId}"`});let r=n.filter(a=>a.eligible),i=n.filter(a=>!a.eligible&&!a.neverGraduate),o=n.filter(a=>a.neverGraduate);return JSON.stringify({summary:{checked:n.length,eligible:r.length,ineligible:i.length,neverGraduate:o.length},...r.length>0?{eligible:r.map(mo),action:"Run `paradigm graduate promote <id>` to graduate eligible habits."}:{},...i.length>0?{ineligible:i.map(mo)}:{},...o.length>0?{neverGraduate:o.map(a=>({id:a.habitId,name:a.habitName,reason:a.reason}))}:{}},null,2)}async function Al(t){let e=fo(t.rootDir),s=Le(t.rootDir),n={hook:[],habit:[],mcp:[]};for(let[r,i]of Object.entries(e.states)){let o=i.tier||"habit";n[o]||(n[o]=[]),n[o].push({id:r,...i.graduatedAt?{graduatedAt:i.graduatedAt}:{},...i.neverGraduate?{neverGraduate:true}:{}});}return JSON.stringify({tiers:{hook:e.hookCount,habit:e.habitCount,mcp:e.mcpCount},neverGraduate:e.neverGraduateCount,estimatedSavingsPerSession:`~${e.hookCount*150} tokens`,byTier:n,thresholds:s.thresholds},null,2)}function yo(){return jl}async function ho(t,e,s){switch(t){case "paradigm_graduate_check":return {handled:true,text:await Ol(s,e)};case "paradigm_graduate_status":return {handled:true,text:await Al(s)};default:return {handled:false,text:""}}}function mo(t){return {id:t.habitId,name:t.habitName,tier:t.currentTier,reason:t.reason,...t.complianceRate!==void 0?{complianceRate:t.complianceRate}:{},...t.eventCount!==void 0?{eventCount:t.eventCount}:{},...t.inCooldown?{inCooldown:true}:{}}}var bo=new Set(["the","a","an","is","how","does","what","why","when","where","do","can","will","should","would","could","are","was","were","been","being","have","has","had","this","that","it","its","of","in","to","for","with","on","at","by","from","or","and","but","not"]),Il=.95,Dl=.3,$l=10;function Hl(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let r=Array.from({length:s+1},()=>Array.from({length:n+1},()=>0));for(let i=0;i<=s;i++)r[i][0]=i;for(let i=0;i<=n;i++)r[0][i]=i;for(let i=1;i<=s;i++)for(let o=1;o<=n;o++){let a=t[i-1]===e[o-1]?0:1;r[i][o]=Math.min(r[i-1][o]+1,r[i][o-1]+1,r[i-1][o-1]+a);}return r[s][n]}function vo(t){let e=t.toLowerCase().split(/\s+/).filter(s=>s.length>0&&!bo.has(s));return e.sort(),e.join(" ")}function Fl(t){try{let e=t.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'aspects_fts'");return e.length>0&&e[0].values.length>0}catch{return false}}function wo(t,e,s){let n=s?.limit??$l,r=vo(e);if(r.length===0)return [];let i=Nl(t,r,s);if(i.length>0)return i.slice(0,n);if(Fl(t)){let a=El(t,r,s);if(a.length>0)return a.slice(0,n)}return ql(t,r,s).slice(0,n)}function Nl(t,e,s){try{let n=`
70
70
  SELECT
71
71
  a.id, a.description, a.category, a.severity, a.tags,
72
72
  sw.weight,
@@ -96,47 +96,47 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
96
96
  hit_count = hit_count + 1,
97
97
  last_hit = ?`,[n,s,r,r]);}catch{return}try{t.run(`UPDATE search_weights
98
98
  SET weight = weight * ?
99
- WHERE query_normalized = ? AND aspect_id != ?`,[Il,n,s]);}catch{}}function Xn(t){try{let e=JSON.parse(t);return Array.isArray(e)&&e.length>0?e:void 0}catch{let e=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.length>0?e:void 0}}function So(){return [{name:"paradigm_aspect_search",description:"Search aspects using three-tier learning search (learned mappings > FTS5 > fuzzy). Returns ranked results. Call paradigm_aspect_confirm after selecting a result to improve future searches. ~200 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:'Search query (natural language or keyword, e.g., "token expiry", "pricing rule")'},limit:{type:"number",description:"Maximum results to return (default: 10)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_get",description:"Get full detail for a single aspect: description, category, severity, code anchors with snippets, edges, and linked lore entries. ~300 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:'Aspect identifier without ~ prefix (e.g., "token-expiry-24h")'}},required:["aspectId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_graph",description:"Traverse the aspect graph from a symbol to visualize its neighborhood. Returns nodes and edges within N hops (BFS). Useful for understanding how aspects relate to each other. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Starting symbol for graph traversal (e.g., "~token-expiry-24h", "#auth-service")'},hops:{type:"number",description:"Maximum number of hops to traverse (default: 2, max: 5)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_heatmap",description:"View the most frequently accessed aspects, ranked by total access count. Shows which aspects are queried most often. ~150 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Maximum entries to return (default: 20)"},accessType:{type:"string",enum:["search","ripple","navigate","direct"],description:"Optional: filter by access type"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_suggest_scan",description:"Scan a source file for implicit aspects (magic numbers, hardcoded limits, configuration values) and suggest aspect definitions. ~200 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:"Relative or absolute path to the source file to scan"}},required:["filePath"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_drift",description:"Smart drift detection for code anchors. Layer 1: normalized hash (ignores formatting). Layer 2: git-aware line mapping (detects shifts, auto-heals .purpose files). ~200 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:"Optional: check a specific aspect. If omitted, checks all aspects."},autoHeal:{type:"boolean",description:"Auto-update anchors for high-confidence shifts (default: true)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_confirm",description:"Confirm a search result to improve future search accuracy. Call this after the user selects or uses a result from paradigm_aspect_search. Reinforces the query-to-aspect mapping. ~50 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The original search query used"},aspectId:{type:"string",description:"The aspect ID that was selected/confirmed"}},required:["query","aspectId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function xo(t,e,s){switch(t){case "paradigm_aspect_search":return Ml(e,s);case "paradigm_aspect_get":return Gl(e,s);case "paradigm_aspect_graph":return Jl(e,s);case "paradigm_aspect_heatmap":return Ul(e,s);case "paradigm_aspect_suggest_scan":return Wl(e,s);case "paradigm_aspect_drift":return zl(e,s);case "paradigm_aspect_confirm":return Bl(e,s);default:return {handled:false,text:""}}}async function Ml(t,e){let{query:s,limit:n=10}=t,r=null;try{r=await c$6(e.rootDir);let i=wo(r,s,{limit:n});for(let c of i)try{j$2(r,c.id,"search");}catch{}let o={query:s,count:i.length,results:i.map(c=>({id:c.id,description:c.description,category:c.category,severity:c.severity,score:Math.round(c.score*1e3)/1e3,tier:c.tier,tags:c.tags,anchorCount:c.anchorCount})),tip:i.length>0?"Call paradigm_aspect_confirm with the query and selected aspectId to improve future searches.":"No results found. Try broader terms or check that aspects are defined in .purpose files."},a=JSON.stringify(o,null,2);return d$9(r,e.rootDir),r=null,O(a.length,"paradigm_aspect_search"),{handled:!0,text:a}}catch(i){if(r)try{d$9(r);}catch{}let o=JSON.stringify({error:"Failed to search aspects",details:String(i),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(o.length,"paradigm_aspect_search"),{handled:true,text:o}}}async function Gl(t,e){let{aspectId:s}=t,n=s.startsWith("~")?s.slice(1):s,r=null;try{r=await c$6(e.rootDir);let i=e$a(r,n);if(i||(i=e$a(r,`~${n}`)),!i){d$9(r),r=null;let f=JSON.stringify({error:"Aspect not found",aspectId:n,suggestion:"Use paradigm_aspect_search to find aspects by keyword."},null,2);return O(f.length,"paradigm_aspect_get"),{handled:!0,text:f}}let o=i.id,c=f$5(r,o).map(f=>{let v=Vl(e.rootDir,f);return {filePath:f.file_path,startLine:f.start_line,endLine:f.end_line,drifted:f.drifted===1,snippet:v}}),l=g$4(r,o),d=h$5(r,o),u=[...l.map(f=>({direction:"outgoing",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin})),...d.map(f=>({direction:"incoming",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin}))],p=[];try{p=await m$4(r,e.rootDir,o);}catch{}try{j$2(r,o,"direct");}catch{}let g;if(i.tags)try{let f=JSON.parse(i.tags);Array.isArray(f)&&(g=f);}catch{g=i.tags.split(",").map(f=>f.trim()).filter(f=>f.length>0);}let m={id:o,description:i.description,category:i.category,severity:i.severity,value:i.value,enforcement:i.enforcement,definedIn:i.defined_in,tags:g,createdAt:i.created_at,updatedAt:i.updated_at,anchors:c,edges:u,lore:p},y=JSON.stringify(m,null,2);return d$9(r,e.rootDir),r=null,O(y.length,"paradigm_aspect_get"),{handled:!0,text:y}}catch(i){if(r)try{d$9(r);}catch{}let o=JSON.stringify({error:"Failed to get aspect",details:String(i),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(o.length,"paradigm_aspect_get"),{handled:true,text:o}}}async function Jl(t,e){let{symbol:s,hops:n=2}=t,r=Math.min(Math.max(n,1),5),i=null;try{i=await c$6(e.rootDir);let o=new Set,a=new Map,c=[],l=[{symbol:s,depth:0}];o.add(s);let d=e$a(i,s);for(a.set(s,{aspectId:s,category:d?.category,severity:d?.severity,depth:0});l.length>0;){let m=l.shift();if(m.depth>=r)continue;let y=i$4(i,m.symbol);for(let f of y){let v=f.source===m.symbol?f.target:f.source;if(c.some(b=>b.source===f.source&&b.target===f.target&&b.relation===f.relation)||c.push({source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin,inferred:f.origin==="inferred"}),!o.has(v)){o.add(v);let b=e$a(i,v);a.set(v,{aspectId:v,category:b?.category,severity:b?.severity,depth:m.depth+1}),l.push({symbol:v,depth:m.depth+1});}}}let u=Array.from(a.values()),p={startSymbol:s,maxHops:r,nodeCount:u.length,edgeCount:c.length,nodes:u,edges:c},g=JSON.stringify(p,null,2);return d$9(i),i=null,O(g.length,"paradigm_aspect_graph"),{handled:!0,text:g}}catch(o){if(i)try{d$9(i);}catch{}let a=JSON.stringify({error:"Failed to traverse aspect graph",details:String(o),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(a.length,"paradigm_aspect_graph"),{handled:true,text:a}}}async function Ul(t,e){let{limit:s=20,accessType:n}=t,r=null;try{r=await c$6(e.rootDir);let i=k$3(r,s*4,n),o=new Map;for(let d of i){let u=o.get(d.aspect_id);if(!u){let p=e$a(r,d.aspect_id);u={aspectId:d.aspect_id,description:p?.description,totalCount:0,byType:{},lastAccessed:d.last_accessed},o.set(d.aspect_id,u);}u.totalCount+=d.count,u.byType[d.access_type]=d.count,d.last_accessed>u.lastAccessed&&(u.lastAccessed=d.last_accessed);}let a=Array.from(o.values()).sort((d,u)=>u.totalCount-d.totalCount).slice(0,s),c={count:a.length,...n?{filteredBy:n}:{},entries:a},l=JSON.stringify(c,null,2);return d$9(r),r=null,O(l.length,"paradigm_aspect_heatmap"),{handled:!0,text:l}}catch(i){if(r)try{d$9(r);}catch{}let o=JSON.stringify({error:"Failed to get aspect heatmap",details:String(i),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(o.length,"paradigm_aspect_heatmap"),{handled:true,text:o}}}async function Wl(t,e){let{filePath:s}=t,n=$.isAbsolute(s)?s:$.join(e.rootDir,s);if(!A.existsSync(n)){let r=JSON.stringify({error:"File not found",filePath:n,suggestion:"Provide a valid relative or absolute file path."},null,2);return O(r.length,"paradigm_aspect_suggest_scan"),{handled:true,text:r}}try{let o=(await import('../utils/aspect-suggest.js')).suggestAspects(n),a={filePath:n,count:o.length,suggestions:o.map(l=>({line:l.line,code:l.code,suggestedName:l.suggestedName,category:l.suggestedCategory,description:l.suggestedDescription,confidence:l.confidence,reason:l.reason,inferred:!0})),tip:o.length>0?"Review suggestions and add confirmed aspects to your .purpose files with ~ prefix and code anchors.":"No implicit aspects detected in this file."},c=JSON.stringify(a,null,2);return O(c.length,"paradigm_aspect_suggest_scan"),{handled:!0,text:c}}catch(r){let i=String(r);if(i.includes("Cannot find module")||i.includes("MODULE_NOT_FOUND")){let a=JSON.stringify({error:"Aspect suggestion engine not available",details:"The aspect-suggest utility has not been implemented yet.",suggestion:"This feature will be available in a future release. For now, manually identify implicit aspects in your code."},null,2);return O(a.length,"paradigm_aspect_suggest_scan"),{handled:true,text:a}}let o=JSON.stringify({error:"Failed to scan for aspect suggestions",details:i},null,2);return O(o.length,"paradigm_aspect_suggest_scan"),{handled:true,text:o}}}async function zl(t,e){let{aspectId:s,autoHeal:n}=t,r=n!==false,i=s?s.startsWith("~")?s.slice(1):s:void 0,o=.7,a=.85;try{let l=$.join(e.rootDir,".paradigm","config.yaml");if(A.existsSync(l)){let u=qe.load(A.readFileSync(l,"utf-8"))?.drift;typeof u?.["suggest-threshold"]=="number"&&(o=u["suggest-threshold"]),typeof u?.["auto-heal-threshold"]=="number"&&(a=u["auto-heal-threshold"]);}}catch{}let c=null;try{c=await c$6(e.rootDir);let l=l$5(c,e.rootDir,i,r,o,a),d=l.filter(w=>w.status==="clean").length,u=l.filter(w=>w.status==="cosmetic").length,p=l.filter(w=>w.status==="shifted").length,g=l.filter(w=>w.status==="modified").length,m=l.filter(w=>w.status==="missing").length,y=g>0||m>0,f=u>0||p>0,v=y?"drift-detected":f?"clean-with-heals":"clean",h={...i?{aspectId:i}:{scope:"all"},totalAnchors:l.length,clean:d,cosmetic:u,shifted:p,modified:g,missing:m,status:v,results:l.map(w=>({aspectId:w.aspectId,path:w.path,startLine:w.startLine,endLine:w.endLine,status:w.status,resolvedBy:w.resolvedBy,exists:w.exists,...w.status==="shifted"?{suggestedStart:w.suggestedStart,suggestedEnd:w.suggestedEnd,autoHealed:w.autoHealed}:{},...w.status==="modified"&&w.currentContent?{currentContent:w.currentContent.slice(0,500)}:{}})),...u>0||p>0?{healed:[u>0?`${u} cosmetic (whitespace/formatting \u2014 hashes updated)`:"",p>0?`${p} shifted (line numbers updated via git diff${r?" \u2014 .purpose files patched":""})`:""].filter(Boolean).join(", ")}:{},...y?{suggestion:"Review drifted anchors to ensure aspects still apply. Run `paradigm scan` to re-materialize after fixing."}:{}},b=JSON.stringify(h,null,2);return d$9(c,e.rootDir),c=null,O(b.length,"paradigm_aspect_drift"),{handled:!0,text:b}}catch(l){if(c)try{d$9(c);}catch{}let d=JSON.stringify({error:"Failed to check aspect drift",details:String(l),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(d.length,"paradigm_aspect_drift"),{handled:true,text:d}}}async function Bl(t,e){let{query:s,aspectId:n}=t,r=null;try{r=await c$6(e.rootDir),ko(r,s,n);let i={confirmed:!0,query:s,aspectId:n,message:`Search mapping reinforced: "${s}" -> ${n}. Future searches for similar queries will rank this aspect higher.`},o=JSON.stringify(i,null,2);return d$9(r,e.rootDir),r=null,O(o.length,"paradigm_aspect_confirm"),{handled:!0,text:o}}catch(i){if(r)try{d$9(r);}catch{}let o=JSON.stringify({error:"Failed to confirm search",details:String(i)},null,2);return O(o.length,"paradigm_aspect_confirm"),{handled:true,text:o}}}function Vl(t,e){let s=$.isAbsolute(e.file_path)?e.file_path:$.join(t,e.file_path);if(!A.existsSync(s))return null;try{let r=A.readFileSync(s,"utf8").split(`
99
+ WHERE query_normalized = ? AND aspect_id != ?`,[Il,n,s]);}catch{}}function Xn(t){try{let e=JSON.parse(t);return Array.isArray(e)&&e.length>0?e:void 0}catch{let e=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.length>0?e:void 0}}function So(){return [{name:"paradigm_aspect_search",description:"Search aspects using three-tier learning search (learned mappings > FTS5 > fuzzy). Returns ranked results. Call paradigm_aspect_confirm after selecting a result to improve future searches. ~200 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:'Search query (natural language or keyword, e.g., "token expiry", "pricing rule")'},limit:{type:"number",description:"Maximum results to return (default: 10)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_get",description:"Get full detail for a single aspect: description, category, severity, code anchors with snippets, edges, and linked lore entries. ~300 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:'Aspect identifier without ~ prefix (e.g., "token-expiry-24h")'}},required:["aspectId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_graph",description:"Traverse the aspect graph from a symbol to visualize its neighborhood. Returns nodes and edges within N hops (BFS). Useful for understanding how aspects relate to each other. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Starting symbol for graph traversal (e.g., "~token-expiry-24h", "#auth-service")'},hops:{type:"number",description:"Maximum number of hops to traverse (default: 2, max: 5)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_heatmap",description:"View the most frequently accessed aspects, ranked by total access count. Shows which aspects are queried most often. ~150 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Maximum entries to return (default: 20)"},accessType:{type:"string",enum:["search","ripple","navigate","direct"],description:"Optional: filter by access type"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_suggest_scan",description:"Scan a source file for implicit aspects (magic numbers, hardcoded limits, configuration values) and suggest aspect definitions. ~200 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:"Relative or absolute path to the source file to scan"}},required:["filePath"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_drift",description:"Smart drift detection for code anchors. Layer 1: normalized hash (ignores formatting). Layer 2: git-aware line mapping (detects shifts, auto-heals .purpose files). ~200 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:"Optional: check a specific aspect. If omitted, checks all aspects."},autoHeal:{type:"boolean",description:"Auto-update anchors for high-confidence shifts (default: true)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_confirm",description:"Confirm a search result to improve future search accuracy. Call this after the user selects or uses a result from paradigm_aspect_search. Reinforces the query-to-aspect mapping. ~50 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The original search query used"},aspectId:{type:"string",description:"The aspect ID that was selected/confirmed"}},required:["query","aspectId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function xo(t,e,s){switch(t){case "paradigm_aspect_search":return Ml(e,s);case "paradigm_aspect_get":return Gl(e,s);case "paradigm_aspect_graph":return Jl(e,s);case "paradigm_aspect_heatmap":return Ul(e,s);case "paradigm_aspect_suggest_scan":return Wl(e,s);case "paradigm_aspect_drift":return zl(e,s);case "paradigm_aspect_confirm":return Bl(e,s);default:return {handled:false,text:""}}}async function Ml(t,e){let{query:s,limit:n=10}=t,r=null;try{r=await c$6(e.rootDir);let i=wo(r,s,{limit:n});for(let c of i)try{j$3(r,c.id,"search");}catch{}let o={query:s,count:i.length,results:i.map(c=>({id:c.id,description:c.description,category:c.category,severity:c.severity,score:Math.round(c.score*1e3)/1e3,tier:c.tier,tags:c.tags,anchorCount:c.anchorCount})),tip:i.length>0?"Call paradigm_aspect_confirm with the query and selected aspectId to improve future searches.":"No results found. Try broader terms or check that aspects are defined in .purpose files."},a=JSON.stringify(o,null,2);return d$9(r,e.rootDir),r=null,O(a.length,"paradigm_aspect_search"),{handled:!0,text:a}}catch(i){if(r)try{d$9(r);}catch{}let o=JSON.stringify({error:"Failed to search aspects",details:String(i),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(o.length,"paradigm_aspect_search"),{handled:true,text:o}}}async function Gl(t,e){let{aspectId:s}=t,n=s.startsWith("~")?s.slice(1):s,r=null;try{r=await c$6(e.rootDir);let i=e$a(r,n);if(i||(i=e$a(r,`~${n}`)),!i){d$9(r),r=null;let f=JSON.stringify({error:"Aspect not found",aspectId:n,suggestion:"Use paradigm_aspect_search to find aspects by keyword."},null,2);return O(f.length,"paradigm_aspect_get"),{handled:!0,text:f}}let o=i.id,c=f$5(r,o).map(f=>{let v=Vl(e.rootDir,f);return {filePath:f.file_path,startLine:f.start_line,endLine:f.end_line,drifted:f.drifted===1,snippet:v}}),l=g$4(r,o),d=h$6(r,o),u=[...l.map(f=>({direction:"outgoing",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin})),...d.map(f=>({direction:"incoming",source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin}))],p=[];try{p=await m$4(r,e.rootDir,o);}catch{}try{j$3(r,o,"direct");}catch{}let g;if(i.tags)try{let f=JSON.parse(i.tags);Array.isArray(f)&&(g=f);}catch{g=i.tags.split(",").map(f=>f.trim()).filter(f=>f.length>0);}let m={id:o,description:i.description,category:i.category,severity:i.severity,value:i.value,enforcement:i.enforcement,definedIn:i.defined_in,tags:g,createdAt:i.created_at,updatedAt:i.updated_at,anchors:c,edges:u,lore:p},y=JSON.stringify(m,null,2);return d$9(r,e.rootDir),r=null,O(y.length,"paradigm_aspect_get"),{handled:!0,text:y}}catch(i){if(r)try{d$9(r);}catch{}let o=JSON.stringify({error:"Failed to get aspect",details:String(i),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(o.length,"paradigm_aspect_get"),{handled:true,text:o}}}async function Jl(t,e){let{symbol:s,hops:n=2}=t,r=Math.min(Math.max(n,1),5),i=null;try{i=await c$6(e.rootDir);let o=new Set,a=new Map,c=[],l=[{symbol:s,depth:0}];o.add(s);let d=e$a(i,s);for(a.set(s,{aspectId:s,category:d?.category,severity:d?.severity,depth:0});l.length>0;){let m=l.shift();if(m.depth>=r)continue;let y=i$3(i,m.symbol);for(let f of y){let v=f.source===m.symbol?f.target:f.source;if(c.some(b=>b.source===f.source&&b.target===f.target&&b.relation===f.relation)||c.push({source:f.source,target:f.target,relation:f.relation,weight:f.weight,origin:f.origin,inferred:f.origin==="inferred"}),!o.has(v)){o.add(v);let b=e$a(i,v);a.set(v,{aspectId:v,category:b?.category,severity:b?.severity,depth:m.depth+1}),l.push({symbol:v,depth:m.depth+1});}}}let u=Array.from(a.values()),p={startSymbol:s,maxHops:r,nodeCount:u.length,edgeCount:c.length,nodes:u,edges:c},g=JSON.stringify(p,null,2);return d$9(i),i=null,O(g.length,"paradigm_aspect_graph"),{handled:!0,text:g}}catch(o){if(i)try{d$9(i);}catch{}let a=JSON.stringify({error:"Failed to traverse aspect graph",details:String(o),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(a.length,"paradigm_aspect_graph"),{handled:true,text:a}}}async function Ul(t,e){let{limit:s=20,accessType:n}=t,r=null;try{r=await c$6(e.rootDir);let i=k$3(r,s*4,n),o=new Map;for(let d of i){let u=o.get(d.aspect_id);if(!u){let p=e$a(r,d.aspect_id);u={aspectId:d.aspect_id,description:p?.description,totalCount:0,byType:{},lastAccessed:d.last_accessed},o.set(d.aspect_id,u);}u.totalCount+=d.count,u.byType[d.access_type]=d.count,d.last_accessed>u.lastAccessed&&(u.lastAccessed=d.last_accessed);}let a=Array.from(o.values()).sort((d,u)=>u.totalCount-d.totalCount).slice(0,s),c={count:a.length,...n?{filteredBy:n}:{},entries:a},l=JSON.stringify(c,null,2);return d$9(r),r=null,O(l.length,"paradigm_aspect_heatmap"),{handled:!0,text:l}}catch(i){if(r)try{d$9(r);}catch{}let o=JSON.stringify({error:"Failed to get aspect heatmap",details:String(i),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(o.length,"paradigm_aspect_heatmap"),{handled:true,text:o}}}async function Wl(t,e){let{filePath:s}=t,n=$.isAbsolute(s)?s:$.join(e.rootDir,s);if(!I.existsSync(n)){let r=JSON.stringify({error:"File not found",filePath:n,suggestion:"Provide a valid relative or absolute file path."},null,2);return O(r.length,"paradigm_aspect_suggest_scan"),{handled:true,text:r}}try{let o=(await import('../utils/aspect-suggest.js')).suggestAspects(n),a={filePath:n,count:o.length,suggestions:o.map(l=>({line:l.line,code:l.code,suggestedName:l.suggestedName,category:l.suggestedCategory,description:l.suggestedDescription,confidence:l.confidence,reason:l.reason,inferred:!0})),tip:o.length>0?"Review suggestions and add confirmed aspects to your .purpose files with ~ prefix and code anchors.":"No implicit aspects detected in this file."},c=JSON.stringify(a,null,2);return O(c.length,"paradigm_aspect_suggest_scan"),{handled:!0,text:c}}catch(r){let i=String(r);if(i.includes("Cannot find module")||i.includes("MODULE_NOT_FOUND")){let a=JSON.stringify({error:"Aspect suggestion engine not available",details:"The aspect-suggest utility has not been implemented yet.",suggestion:"This feature will be available in a future release. For now, manually identify implicit aspects in your code."},null,2);return O(a.length,"paradigm_aspect_suggest_scan"),{handled:true,text:a}}let o=JSON.stringify({error:"Failed to scan for aspect suggestions",details:i},null,2);return O(o.length,"paradigm_aspect_suggest_scan"),{handled:true,text:o}}}async function zl(t,e){let{aspectId:s,autoHeal:n}=t,r=n!==false,i=s?s.startsWith("~")?s.slice(1):s:void 0,o=.7,a=.85;try{let l=$.join(e.rootDir,".paradigm","config.yaml");if(I.existsSync(l)){let u=qe.load(I.readFileSync(l,"utf-8"))?.drift;typeof u?.["suggest-threshold"]=="number"&&(o=u["suggest-threshold"]),typeof u?.["auto-heal-threshold"]=="number"&&(a=u["auto-heal-threshold"]);}}catch{}let c=null;try{c=await c$6(e.rootDir);let l=l$5(c,e.rootDir,i,r,o,a),d=l.filter(w=>w.status==="clean").length,u=l.filter(w=>w.status==="cosmetic").length,p=l.filter(w=>w.status==="shifted").length,g=l.filter(w=>w.status==="modified").length,m=l.filter(w=>w.status==="missing").length,y=g>0||m>0,f=u>0||p>0,v=y?"drift-detected":f?"clean-with-heals":"clean",h={...i?{aspectId:i}:{scope:"all"},totalAnchors:l.length,clean:d,cosmetic:u,shifted:p,modified:g,missing:m,status:v,results:l.map(w=>({aspectId:w.aspectId,path:w.path,startLine:w.startLine,endLine:w.endLine,status:w.status,resolvedBy:w.resolvedBy,exists:w.exists,...w.status==="shifted"?{suggestedStart:w.suggestedStart,suggestedEnd:w.suggestedEnd,autoHealed:w.autoHealed}:{},...w.status==="modified"&&w.currentContent?{currentContent:w.currentContent.slice(0,500)}:{}})),...u>0||p>0?{healed:[u>0?`${u} cosmetic (whitespace/formatting \u2014 hashes updated)`:"",p>0?`${p} shifted (line numbers updated via git diff${r?" \u2014 .purpose files patched":""})`:""].filter(Boolean).join(", ")}:{},...y?{suggestion:"Review drifted anchors to ensure aspects still apply. Run `paradigm scan` to re-materialize after fixing."}:{}},b=JSON.stringify(h,null,2);return d$9(c,e.rootDir),c=null,O(b.length,"paradigm_aspect_drift"),{handled:!0,text:b}}catch(l){if(c)try{d$9(c);}catch{}let d=JSON.stringify({error:"Failed to check aspect drift",details:String(l),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return O(d.length,"paradigm_aspect_drift"),{handled:true,text:d}}}async function Bl(t,e){let{query:s,aspectId:n}=t,r=null;try{r=await c$6(e.rootDir),ko(r,s,n);let i={confirmed:!0,query:s,aspectId:n,message:`Search mapping reinforced: "${s}" -> ${n}. Future searches for similar queries will rank this aspect higher.`},o=JSON.stringify(i,null,2);return d$9(r,e.rootDir),r=null,O(o.length,"paradigm_aspect_confirm"),{handled:!0,text:o}}catch(i){if(r)try{d$9(r);}catch{}let o=JSON.stringify({error:"Failed to confirm search",details:String(i)},null,2);return O(o.length,"paradigm_aspect_confirm"),{handled:true,text:o}}}function Vl(t,e){let s=$.isAbsolute(e.file_path)?e.file_path:$.join(t,e.file_path);if(!I.existsSync(s))return null;try{let r=I.readFileSync(s,"utf8").split(`
100
100
  `),i=Math.max(0,e.start_line-1),o=Math.min(r.length,e.end_line),a=r.slice(i,o).join(`
101
101
  `);return a.length>1e3?a.slice(0,1e3)+`
102
- ... (truncated)`:a}catch{return null}}function Co(){return [{name:"paradigm_task_create",description:"Create a task (persistent scratch-pad item that survives context windows). Returns the created task ID. ~100 tokens.",inputSchema:{type:"object",properties:{blurb:{type:"string",description:"One-line task description"},priority:{type:"string",enum:["high","medium","low"],description:"Priority level (default: medium)"},tags:{type:"array",items:{type:"string"},description:"Tags \u2014 symbols (#component), freeform labels, etc."},related_lore:{type:"array",items:{type:"string"},description:"Linked lore entry IDs"},claimant:{type:"object",description:"Owner of this task (v7 DAG). kind: archetype|human|peer; ref: role id / git user / agentId",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},parentTaskId:{type:"string",description:"Parent task id (v7 DAG edge)"},dependsOn:{type:"array",items:{type:"string"},description:"Task ids this task depends on (v7 DAG edges)"},stage:{type:"number",description:"Orchestration stage index (v7 DAG)"},external_ref:{type:"object",description:"External anchor (renamed from session_link). kind: github|session|symphony|orchestration|url",properties:{kind:{type:"string",enum:["github","session","symphony","orchestration","url"]},ref:{type:"string"}}},session_link:{type:"string",description:"(Deprecated \u2014 use external_ref) Legacy external anchor; aliased to external_ref"}},required:["blurb"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_list",description:"List/filter tasks by status, priority, tags, or symbols. Returns task list sorted by priority then date. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["open","in-progress","done","shelved","active","all"],description:"Filter by status (default: open). 'active' = open \u222A in-progress"},priority:{type:"string",enum:["high","medium","low"],description:"Filter by priority"},tag:{type:"string",description:"Filter by tag (symbol or freeform)"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_task_update",description:"Update a task (blurb, priority, status, tags). Returns updated task. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Task ID (e.g., "T-2026-02-26-001")'},blurb:{type:"string",description:"New description"},priority:{type:"string",enum:["high","medium","low"]},status:{type:"string",enum:["open","in-progress","done","shelved"]},tags:{type:"array",items:{type:"string"},description:"Replace tags"},related_lore:{type:"array",items:{type:"string"},description:"Related lore entry IDs (includes former assessment entries)"},related_assessments:{type:"array",items:{type:"string"},description:"(Deprecated \u2014 use related_lore) Alias for related_lore"},claimant:{type:"object",description:"Owner of this task (v7 DAG). kind: archetype|human|peer; ref: role id / git user / agentId",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},parentTaskId:{type:"string",description:"Parent task id (v7 DAG edge)"},dependsOn:{type:"array",items:{type:"string"},description:"Task ids this task depends on (v7 DAG edges)"},stage:{type:"number",description:"Orchestration stage index (v7 DAG)"},external_ref:{type:"object",description:"External anchor (renamed from session_link). kind: github|session|symphony|orchestration|url",properties:{kind:{type:"string",enum:["github","session","symphony","orchestration","url"]},ref:{type:"string"}}},session_link:{type:"string",description:"(Deprecated \u2014 use external_ref) Legacy external anchor; aliased to external_ref"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_done",description:"Mark a task as done. Shorthand for update with status=done. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_shelve",description:"Shelve a task (not now, not never). Shorthand for update with status=shelved. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Ro(t,e,s){switch(t){case "paradigm_task_create":{let n=await e$4(s.rootDir,{blurb:e.blurb,priority:e.priority,tags:e.tags,related_lore:e.related_lore,claimant:e.claimant,parentTaskId:e.parentTaskId,dependsOn:e.dependsOn,stage:e.stage,external_ref:e.external_ref,session_link:e.session_link}),r=await d$4(s.rootDir,n);return {handled:true,text:JSON.stringify({created:n,task:r},null,2)}}case "paradigm_task_list":{let n=await c$3(s.rootDir,{status:e.status||"open",priority:e.priority,tag:e.tag,limit:e.limit||20}),r=e.status||"open",i=[`${n.length} ${r} task(s):`];for(let o of n){let a=o.tags.length>0?` [${o.tags.join(", ")}]`:"";i.push(` [${o.priority}] ${o.id}: ${o.blurb}${a}`);}return {handled:true,text:i.join(`
103
- `)}}case "paradigm_task_update":{let n=e.id,r={};if(e.blurb!==void 0&&(r.blurb=e.blurb),e.priority!==void 0&&(r.priority=e.priority),e.status!==void 0&&(r.status=e.status),e.tags!==void 0&&(r.tags=e.tags),e.related_lore!==void 0&&(r.related_lore=e.related_lore),e.related_assessments!==void 0&&(r.related_assessments=e.related_assessments),e.claimant!==void 0&&(r.claimant=e.claimant),e.parentTaskId!==void 0&&(r.parentTaskId=e.parentTaskId),e.dependsOn!==void 0&&(r.dependsOn=e.dependsOn),e.stage!==void 0&&(r.stage=e.stage),e.external_ref!==void 0&&(r.external_ref=e.external_ref),e.session_link!==void 0&&e.external_ref===void 0){let a=e.session_link,c=a.toLowerCase(),l=c.includes("github")?"github":c.includes("session")?"session":"url";r.external_ref={kind:l,ref:a};}if(!await f$1(s.rootDir,n,r))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let o=await d$4(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,task:o},null,2)}}case "paradigm_task_done":{let n=e.id;if(!await g$2(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let i=await d$4(s.rootDir,n);return {handled:true,text:JSON.stringify({completed:n,task:i,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let n=e.id;if(!await h$2(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let i=await d$4(s.rootDir,n);return {handled:true,text:JSON.stringify({shelved:n,task:i},null,2)}}default:return {handled:false,text:""}}}var Po=0;function To(){let t=new Date().toISOString().slice(0,10);return Po++,`run_${t}_${String(Po).padStart(3,"0")}`}var jo=/\{\{([^}]+)\}\}/g;function Me(t,e){if(typeof t=="string")return t.replace(jo,(s,n)=>{let r=Yl(n.trim(),e);return r!==void 0?String(r):s});if(Array.isArray(t))return t.map(s=>Me(s,e));if(t&&typeof t=="object"){let s={};for(let[n,r]of Object.entries(t))s[n]=Me(r,e);return s}return t}function Yl(t,e){let[s,...n]=t.split("."),r=n.join(".");switch(s){case "fixtures":return e.fixtures[r];case "produces":return Qn(e.produces,r);case "context":case "parent":return e.context[r];case "env":return e.env[r]??process.env[r];default:return}}function Qn(t,e){let s=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let r of s){if(n==null||typeof n!="object")return;n=n[r];}return n}function Kl(t,e){let s={};for(let[n,r]of Object.entries(t)){let i=r.match(/\{\{response\.(.+)\}\}/);if(i){let o=i[1],a=Qn(e,o);a!==void 0&&(s[n]=a);}}return s}function Xl(t,e){if(e.status!==t.status)return {pass:false,failure:`Status mismatch: expected ${t.status}, got ${e.status}`};if(t.body){let s=e.body;if(t.body.has){for(let n of t.body.has)if(s===null||typeof s!="object"||!(n in s))return {pass:false,failure:`Expected body to have key "${n}"`}}if(t.body.match)for(let[n,r]of Object.entries(t.body.match)){let i=Qn(s,n);if(JSON.stringify(i)!==JSON.stringify(r))return {pass:false,failure:`Body mismatch at "${n}": expected ${JSON.stringify(r)}, got ${JSON.stringify(i)}`}}}return {pass:true}}async function Ql(t,e,s){let n=Date.now(),r=t.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!r)return {id:t.id,status:"fail",route:t.route,gates:t.gates,failure:`Invalid route format: ${t.route}`,duration_ms:Date.now()-n};let i=r[1],o=r[2],a=Me(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...t.headers?Me(t.headers,s):{}},d=t.payload?Me(t.payload,s):void 0,u={url:c,method:i,headers:t.headers?l:void 0,payload:d};if(e.dryRun)return {id:t.id,status:"pass",route:t.route,gates:t.gates,request:u,produced:t.produces?Object.fromEntries(Object.keys(t.produces).map(p=>[p,`<dry-run:${p}>`])):void 0,duration_ms:Date.now()-n};try{let p={method:i,headers:l};d&&["POST","PUT","PATCH"].includes(i)&&(p.body=JSON.stringify(d));let g=await fetch(c,p),m;(g.headers.get("content-type")||"").includes("application/json")?m=await g.json():m=await g.text();let f={status:g.status,body:m},v=Xl(t.expect,f),h;t.produces&&v.pass&&(h=Kl(t.produces,m));let b;return (g.status===401||g.status===403)&&(b=t.gates[t.gates.length-1]),{id:t.id,status:v.pass?"pass":"fail",route:t.route,gates:t.gates,request:u,response:f,produced:h,expected_status:v.pass?void 0:t.expect.status,failure:v.failure,gate_that_blocked:b,duration_ms:Date.now()-n}}catch(p){return {id:t.id,status:"fail",route:t.route,gates:t.gates,request:u,failure:`Request failed: ${p.message}`,duration_ms:Date.now()-n}}}async function Oo(t,e,s){let n=Date.now(),r=await c$4(t,e);return r?Ao(t,r,s):{persona:e,run_id:To(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-n}}async function Ao(t,e,s){let n=Date.now(),r=s.stopOnFailure!==false,i={fixtures:e.fixtures||{},produces:{},context:s.context||{},env:process.env},o=[],a=[],c=[],l=false;for(let y of e.journey){if(l&&r){if(o.push({id:y.id,status:"skip",route:y.route,gates:y.gates,duration_ms:0}),y.spawns)for(let v of y.spawns)c.push(v.persona);continue}let f=await Ql(y,s,i);if(o.push(f),f.status==="pass"){if(f.produced&&Object.assign(i.produces,f.produced),y.spawns)for(let v of y.spawns)a.push(v.persona);}else if(l=true,y.spawns)for(let v of y.spawns)c.push(v.persona);}let d=o.filter(y=>y.status==="pass").length,u=o.filter(y=>y.status==="fail").length,p=e.journey.length,g=o.find(y=>y.status==="fail"),m;return u===0?m=`${d}/${p} passed. All steps succeeded.`:m=`${d}/${p} passed. Failed at step ${o.indexOf(g)+1} (${g.id}): ${g.failure}`,{persona:e.id,run_id:To(),status:u>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-n}}async function Io(t,e,s){let n=Date.now(),r=await import('fs'),i=await import('path'),o=await import('js-yaml'),a=i.join(t,".paradigm","personas","chains",`${e}.yaml`);if(!r.existsSync(a))return {chain_id:e,status:"error",persona_results:[],summary:`Chain ${e} not found`,duration_ms:Date.now()-n};let c=o.load(r.readFileSync(a,"utf8")),l;if(s.permutation&&c.permutations&&(l=c.permutations.find(y=>y.id===s.permutation),!l))return {chain_id:e,status:"error",persona_results:[],summary:`Permutation ${s.permutation} not found in chain ${e}`,duration_ms:Date.now()-n};let d=[],u={},p=s.stopOnFailure!==false;for(let y of c.order){let f=await c$4(t,y.persona);if(!f){if(d.push({persona:y.persona,status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${y.persona} not found`,duration_ms:0}),p)break;continue}if(l&&l.overrides[y.persona]){let w=l.overrides[y.persona];if(w.traits&&(f.traits={...f.traits,...w.traits}),w.journey)for(let[x,k]of Object.entries(w.journey)){let _=f.journey.find(T=>T.id===x);_&&(k.payload&&(_.payload={..._.payload,...k.payload}),k.expect&&(_.expect={..._.expect,...k.expect}));}}let v={};if(y.wait_for){let[w,x]=y.wait_for.split("."),k=d.find(T=>T.persona===w);if(k){let T=k.steps.find(C=>C.id===x);T?.produced&&(v=Object.fromEntries(Object.entries(T.produced).map(([C,j])=>[C,String(j)])));}let _=await c$4(t,w);if(_){let T=_.journey.find(C=>C.id===x);if(T?.spawns){let C=T.spawns.find(j=>j.persona===y.persona);if(C?.context){let j=u[w]||{};for(let[O,R]of Object.entries(C.context))v[O]=String(Me(R,{fixtures:{},produces:j,context:{},env:process.env}));}}}}let h=await Ao(t,f,{...s,context:v});d.push(h);let b={};for(let w of h.steps)w.produced&&Object.assign(b,w.produced);if(u[y.persona]=b,h.status==="fail"&&p)break}let g=d.filter(y=>y.status==="pass").length,m=c.order.length;return {chain_id:e,status:d.some(y=>y.status!=="pass")?"fail":"pass",persona_results:d,summary:`${g}/${m} personas passed.`,duration_ms:Date.now()-n}}function Do(t){let e=[],s=new Set;for(let n of t.journey){let i=JSON.stringify(n).match(jo)||[];for(let o of i){let a=o.replace("{{","").replace("}}","").trim(),[c,...l]=a.split("."),d=l.join(".");switch(c){case "fixtures":!t.fixtures||d in t.fixtures;break;case "produces":s.has(d)||e.push({step:n.id,template:o,error:`{{produces.${d}}} used but not produced by a prior step`});break;case "context":case "parent":break;case "env":break;case "response":break;default:e.push({step:n.id,template:o,error:`Unknown namespace "${c}" in ${o}`});}}if(n.produces)for(let o of Object.keys(n.produces))s.add(o);}return {valid:e.length===0,errors:e}}var Ho="paradigm-personas",Zl={id:Ho,version:"1.0",name:"Paradigm Personas",description:"Events from persona journey and chain execution",scope:{key:"persona_id",label:"Persona"},eventTypes:{"persona.run.start":{category:"lifecycle",severity:"info"},"persona.step.pass":{category:"assertion",severity:"info"},"persona.step.fail":{category:"assertion",severity:"warning"},"persona.step.skip":{category:"lifecycle",severity:"info"},"persona.run.complete":{category:"lifecycle",severity:"info"},"persona.chain.complete":{category:"lifecycle",severity:"info"},"persona.coverage.report":{category:"analysis",severity:"info"}}},Zn=false;async function $o(t){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!Zn)try{s.registerSchema(Zl),Zn=!0;}catch{Zn=!0;}let n=[];if("persona"in t){let r=t;n.push({type:"persona.run.start",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,total_steps:r.steps.length}});for(let i of r.steps){let o=i.status==="pass"?"persona.step.complete":`persona.step.${i.status}`;n.push({type:o,timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,step_id:i.id,route:i.route,gates:i.gates,gates_traversed:i.gates,status:i.response?.status,body:i.response?.body,signals_fired:[],duration_ms:i.duration_ms,failure:i.failure,gate_that_blocked:i.gate_that_blocked,produced_keys:i.produced?Object.keys(i.produced):[]}});}n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,status:r.status,total_steps:r.steps.length,passed:r.steps.filter(i=>i.status==="pass").length,failed:r.steps.filter(i=>i.status==="fail").length,skipped:r.steps.filter(i=>i.status==="skip").length,duration_ms:r.duration_ms,spawns_triggered:r.spawns_triggered,spawns_blocked:r.spawns_blocked}});}else {let r=t;for(let i of r.persona_results)n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,chain_id:r.chain_id,status:i.status,total_steps:i.steps.length,passed:i.steps.filter(o=>o.status==="pass").length,failed:i.steps.filter(o=>o.status==="fail").length,duration_ms:i.duration_ms}});n.push({type:"persona.chain.complete",timestamp:new Date().toISOString(),data:{chain_id:r.chain_id,status:r.status,personas_run:r.persona_results.length,personas_passed:r.persona_results.filter(i=>i.status==="pass").length,duration_ms:r.duration_ms}});}n.length>0&&s.insertEventBatch(Ho,"paradigm-personas",n);}catch{}}function Fo(){return [{name:"paradigm_persona_create",description:"Create a persona \u2014 named test actor with traits, trigger, fixtures, and journey steps. Writes a .persona file. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Persona ID (kebab-case, e.g., "alice-admin")'},name:{type:"string",description:'Human-readable name (e.g., "Agency Owner (Annual Billing)")'},description:{type:"string",description:"What this persona represents"},traits:{type:"object",description:"Key-value actor attributes (tier, billing, role, etc.)"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"],description:"How this persona enters the system"},spawned_by:{type:"string",description:"persona-id.step-id (required if type != root)"},context:{type:"object",description:"Data passed from parent spawn"}},required:["type"]},fixtures:{type:"object",description:"Test data for this persona (email, password, API keys, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering"},journey:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case)"},description:{type:"string"},route:{type:"string",description:'METHOD /path (e.g., "POST /api/auth/signup")'},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object",description:"Request body. Supports {{produces.X}} and {{fixtures.X}} interpolation."},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object",properties:{has:{type:"array",items:{type:"string"}},match:{type:"object"}}}},required:["status"]},produces:{type:"object",description:"Values to extract from response for later steps"},spawns:{type:"array",items:{type:"object",properties:{persona:{type:"string"},via:{type:"string"},context:{type:"object"}},required:["persona","via"]}},signals:{type:"array",items:{type:"string"},description:"!signal references expected to fire"}},required:["id","route","gates","expect"]}}},required:["id","name","trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_get",description:"Get full persona detail \u2014 journey, traits, spawn chain, validation status. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_list",description:"List personas with optional filters \u2014 tag, trigger type, gate, flow. ~200 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:"Filter by tag"},trigger_type:{type:"string",enum:["root","invitation","signup","api"],description:"Filter by trigger type"},gate:{type:"string",description:"Filter by gate (show personas that traverse this gate)"},flow:{type:"string",description:"Filter by flow (show personas that exercise this flow)"},limit:{type:"number",description:"Maximum results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_update",description:"Update persona fields \u2014 traits, fixtures, journey steps, tags. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"},name:{type:"string"},description:{type:"string"},traits:{type:"object"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"]},spawned_by:{type:"string"},context:{type:"object"}}},fixtures:{type:"object"},tags:{type:"array",items:{type:"string"}},journey:{type:"array",description:"Replace entire journey. Use paradigm_persona_add_step for surgical edits."}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_delete",description:"Delete a persona. Warns if other personas spawn from it. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_add_step",description:"Add a journey step to a persona. Validates gates, route format, and produce/consume chains. ~150 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case, unique within persona)"},description:{type:"string"},route:{type:"string",description:"METHOD /path"},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object"},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object"}},required:["status"]},produces:{type:"object"},spawns:{type:"array"},signals:{type:"array",items:{type:"string"}}},required:["id","route","gates","expect"]},after:{type:"string",description:"Insert after this step ID. Omit to append."}},required:["persona_id","step"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_remove_step",description:"Remove a journey step. Warns if it produces data consumed by later steps or spawns other personas. ~100 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step_id:{type:"string",description:"Step ID to remove"}},required:["persona_id","step_id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_validate",description:"Full persona validation \u2014 schema + cross-refs + Sentinel event matching with exact assertion results. Compares expected journey outcomes against actual Sentinel events. ~300 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Validate one persona. Omit for all."},deep:{type:"boolean",description:"Include cross-reference and coverage analysis (default: false)"},sentinel:{type:"boolean",description:"Compare against Sentinel events (default: true when available)"},run_id:{type:"string",description:"Validate against a specific run. Omit for latest."},chain_id:{type:"string",description:"Validate against a specific chain execution."},environment:{type:"string",description:"Filter Sentinel events by environment (dev, staging, prod, ci)."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_coverage",description:"Coverage report \u2014 which routes/gates/flows have persona coverage, which don't. Compares against portal.yaml. ~250 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_affected",description:"Given a symbol (^gate, $flow, route), return affected personas and their steps. Used by ripple. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to check (e.g., "^authenticated", "$checkout-flow", "POST /api/orders")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_run",description:"Execute a persona journey or chain against a running server. Interpolates templates, sends requests step-by-step, validates responses. Supports dry-run mode. ~500 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Run a single persona journey"},chain_id:{type:"string",description:"Run a named chain (overrides persona_id)"},base_url:{type:"string",description:'Server base URL (e.g., "http://localhost:3000")'},dry_run:{type:"boolean",description:"Validate and interpolate without making requests (default: false)"},stop_on_failure:{type:"boolean",description:"Stop on first failing step (default: true)"},permutation:{type:"string",description:"Permutation ID from chain definition"}},required:["base_url"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function No(t,e,s){switch(t){case "paradigm_persona_create":try{let n=await d$5(s.rootDir,{id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags,journey:e.journey}),r=await c$4(s.rootDir,n);return {handled:!0,text:JSON.stringify({created:n,persona:r},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_get":{let n=e.id,r=await c$4(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let i=await i$1(s.rootDir,r);return {handled:true,text:JSON.stringify({persona:r,validation:i},null,2)}}case "paradigm_persona_list":{let n=await b$8(s.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),r=n.map(i=>({id:i.id,name:i.name,trigger:i.trigger.type,steps:i.journey.length,gates:[...new Set(i.journey.flatMap(o=>o.gates))],tags:i.tags||[]}));return {handled:true,text:JSON.stringify({count:n.length,personas:r},null,2)}}case "paradigm_persona_update":{let n=e.id,r={};if(e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),e.traits!==void 0&&(r.traits=e.traits),e.trigger!==void 0&&(r.trigger=e.trigger),e.fixtures!==void 0&&(r.fixtures=e.fixtures),e.tags!==void 0&&(r.tags=e.tags),e.journey!==void 0&&(r.journey=e.journey),!await e$5(s.rootDir,n,r))return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let o=await c$4(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,persona:o},null,2)}}case "paradigm_persona_delete":{let n=e.id,r=await f$2(s.rootDir,n);return r.deleted?{handled:true,text:JSON.stringify({deleted:n,warnings:r.warnings,hint:r.warnings.length>0?"Other personas reference this one. Update or delete them to avoid broken spawn chains.":void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Persona ${n} not found`})}}case "paradigm_persona_add_step":try{if(!await g$3(s.rootDir,e.persona_id,e.step,e.after))return {handled:!0,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let r=await c$4(s.rootDir,e.persona_id);return {handled:!0,text:JSON.stringify({added:e.step.id,persona_id:e.persona_id,total_steps:r?.journey.length},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_remove_step":{let n=await h$3(s.rootDir,e.persona_id,e.step_id);return n.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:n.warnings},null,2)}:{handled:true,text:JSON.stringify({error:`Step ${e.step_id} not found in persona ${e.persona_id}`})}}case "paradigm_persona_validate":{let n=e.deep??false,r=e.sentinel??true,i={run_id:e.run_id,chain_id:e.chain_id,environment:e.environment};if(e.persona_id){let d=await c$4(s.rootDir,e.persona_id);if(!d)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let u=await i$1(s.rootDir,d,n);if(r)try{let p=await m$2(d,i);u.sentinel_assertions=p,(p.summary.failed>0||p.summary.unmatched>0)&&(u.valid=!1);}catch{}return {handled:true,text:JSON.stringify(u,null,2)}}let o=await b$8(s.rootDir),a=await Promise.all(o.map(async d=>{let u=await i$1(s.rootDir,d,n);if(r)try{let p=await m$2(d,i);u.sentinel_assertions=p,(p.summary.failed>0||p.summary.unmatched>0)&&(u.valid=!1);}catch{}return u})),c=a.filter(d=>d.valid).length,l=a.filter(d=>!d.valid).length;return {handled:true,text:JSON.stringify({total:a.length,valid:c,invalid:l,results:a.filter(d=>!d.valid||d.warnings.length>0||d.sentinel_assertions)},null,2)}}case "paradigm_persona_coverage":{let n=await k$2(s.rootDir);return {handled:true,text:JSON.stringify(n,null,2)}}case "paradigm_persona_affected":{let n=e.symbol,r=await l$2(s.rootDir,n);return r.length===0?{handled:true,text:JSON.stringify({symbol:n,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:n,affected:r},null,2)}}case "paradigm_persona_run":{let n=e.base_url,r=e.dry_run??false,i=e.stop_on_failure??true;if(e.chain_id){let o=await Io(s.rootDir,e.chain_id,{baseUrl:n,dryRun:r,stopOnFailure:i,permutation:e.permutation});return r||await $o(o),{handled:true,text:JSON.stringify(o,null,2)}}if(e.persona_id){let o=await c$4(s.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let a=Do(o);if(!a.valid&&!r)return {handled:true,text:JSON.stringify({error:"Template interpolation errors \u2014 fix before running",errors:a.errors,hint:"Use dry_run: true to see interpolated values without executing requests"},null,2)};let c=await Oo(s.rootDir,e.persona_id,{baseUrl:n,dryRun:r,stopOnFailure:i});return r||await $o(c),{handled:true,text:JSON.stringify(c,null,2)}}return {handled:true,text:JSON.stringify({error:"Either persona_id or chain_id is required"})}}default:return {handled:false,text:""}}}var ed=".paradigm/graphs",nr={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},er=200,tr=60,Ge=20,Vt=40,Eo=50,td=60;function Lo(){return [{name:"paradigm_graph_generate",description:"Generate a named GraphState JSON file for the Paradigm Symbol Graph UI. Writes to .paradigm/graphs/{name}.graph.json. View saved graphs with `paradigm graph` CLI. Returns a summary with node/edge counts and file path. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Graph name (kebab-case). Used as filename: {name}.graph.json. E.g. "auth-flow", "full-project", "checkout-subsystem".'},symbols:{type:"array",items:{type:"string"},description:'Symbol names to include (e.g. ["#auth-middleware", "^authenticated"]). Omit to include all from scan-index.'},groups:{type:"array",items:{type:"object",properties:{label:{type:"string",description:"Group display label"},symbols:{type:"array",items:{type:"string"},description:"Symbol names belonging to this group"}},required:["label","symbols"]},description:"Optional groupings of symbols."},links:{type:"array",items:{type:"object",properties:{source:{type:"string",description:"Source group label"},target:{type:"string",description:"Target group label"},label:{type:"string",description:"Edge label"}},required:["source","target"]},description:"Edges between groups (by label name)."}},required:["name"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Mo(t,e,s){if(t!=="paradigm_graph_generate")return {handled:false,text:""};try{let n=e.name||"untitled",r=n.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),i=sd(s.rootDir,e.symbols,e.groups,e.links,n),o=JSON.stringify(i,null,2),a=$.join(s.rootDir,ed);A.existsSync(a)||A.mkdirSync(a,{recursive:!0});let c=$.join(a,`${r}.graph.json`);A.writeFileSync(c,o,"utf8");let l=JSON.stringify({file:c,name:n,slug:r,nodes:i.nodes.length,edges:i.edges.length,size:`${(o.length/1024).toFixed(1)} KB`,hint:"Graph saved. Run `paradigm graph` to view in browser."},null,2);return O(l.length,t),{handled:!0,text:l}}catch(n){let r=JSON.stringify({error:n.message},null,2);return O(r.length,t),{handled:true,text:r}}}var nd={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function rd(t){let e=$.join(t,".paradigm","scan-index.json");if(!A.existsSync(e))return [];let s=JSON.parse(A.readFileSync(e,"utf8")),n=[];for(let[r,i]of Object.entries(nd)){let o=s[r];if(!(!o||typeof o!="object"))for(let[a,c]of Object.entries(o)){let l=c;n.push({id:a,name:a,category:i,prefix:nr[i]||"#",description:l.description,path:l.path,tags:l.tags});}}return n}function qo(t,e){let s=t.replace(/^[#$^!~]/,"");return e.find(n=>n.id===s||n.name===s||n.id===t||n.name===t)}function sd(t,e,s,n,r="Generated Graph"){let i=rd(t),o;e&&e.length>0?o=e.map(g=>qo(g,i)).filter(Boolean):o=i;let a=[],c=[],l=new Map,d=new Set,u=0;if(s&&s.length>0)for(let g of s){let m=`group-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;l.set(g.label,m);let y=g.symbols.map(k=>qo(k,o)).filter(Boolean),f=Math.ceil(Math.sqrt(y.length)),v=Math.ceil(y.length/f);for(let k=0;k<y.length;k++){let _=y[k],T=k%f,C=Math.floor(k/f),j=nr[_.category]||"#";a.push({id:`sym-${_.id}`,type:"symbolNode",position:{x:Vt+T*(er+Ge),y:Eo+Vt+C*(tr+Ge)},parentId:m,data:{type:"symbol",symbol:_,label:`${j}${_.name}`}}),d.add(_.id);}let h=Math.max(f,1),b=Math.max(v,1),w=Vt*2+h*er+(h-1)*Ge,x=Eo+Vt*2+b*tr+(b-1)*Ge;a.unshift({id:m,type:"groupNode",position:{x:u,y:0},style:{width:w,height:x},data:{type:"group",label:g.label}}),u+=w+td;}let p=o.filter(g=>!d.has(g.id));if(p.length>0){let g=s&&s.length>0?400:0,m=Math.ceil(Math.sqrt(p.length));for(let y=0;y<p.length;y++){let f=p[y],v=y%m,h=Math.floor(y/m),b=nr[f.category]||"#";a.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:v*(er+Ge),y:g+h*(tr+Ge)},data:{type:"symbol",symbol:f,label:`${b}${f.name}`}});}}if(n&&n.length>0)for(let g of n){let m=l.get(g.source),y=l.get(g.target);m&&y&&c.push({id:`e-${m}-${y}`,source:m,target:y,type:"default",label:g.label,data:{label:g.label}});}return {version:"1.0",name:r,projectId:$.basename(t),lastModified:new Date().toISOString(),nodes:a,edges:c}}var te=["specify","plan","task","implement","validate"],ht=".paradigm/pipeline",Go={"add-feature":{gates:{specify:"manual",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Standard feature addition with manual spec/plan review"},"bug-fix":{gates:{specify:"auto",plan:"auto",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Quick bug fix with automated gates except validation"},"security-change":{gates:{specify:"manual",plan:"manual",task:"manual",implement:"manual",validate:"manual"},description:"Security-sensitive change with all-manual gates"},refactor:{gates:{specify:"auto",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Code refactoring with manual plan review"}};function Yt(t){return t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function mt(t,e){let s=Yt(e),n=$.join(t,ht,`${s}.yaml`);return A.existsSync(n)?qe.load(A.readFileSync(n,"utf8")):null}function yt(t,e){let s=Yt(e.feature),n=$.join(t,ht);A.existsSync(n)||A.mkdirSync(n,{recursive:true});let r=$.join(n,`${s}.yaml`);return A.writeFileSync(r,qe.dump(e,{lineWidth:120}),"utf8"),r}function Jo(t){let e=$.join(t,ht);return A.existsSync(e)?A.readdirSync(e).filter(s=>s.endsWith(".yaml")&&!s.startsWith("completed")).map(s=>{try{return qe.load(A.readFileSync($.join(e,s),"utf8"))}catch{return null}}).filter(Boolean):[]}function id(t,e,s){let n={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return n.specify.status="in-progress",{version:"1.0",feature:Yt(t),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:s,stages:n}}function od(t){let e=te.indexOf(t);return e<te.length-1?te[e+1]:null}function Uo(t,e){let s=Yt(e.feature),n=$.join(t,ht,"completed");A.existsSync(n)||A.mkdirSync(n,{recursive:true});let r=$.join(n,`${s}.yaml`);A.writeFileSync(r,qe.dump(e,{lineWidth:120}),"utf8");let i=$.join(t,ht,`${s}.yaml`);A.existsSync(i)&&A.unlinkSync(i);}function Wo(){return [{name:"paradigm_pipeline_start",description:"Create a new spec pipeline for a feature. Uses templates (add-feature, bug-fix, security-change, refactor) or custom gate config. Returns pipeline state. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name or description (will be slugified)"},template:{type:"string",enum:["add-feature","bug-fix","security-change","refactor"],description:"Pipeline template (default: add-feature)"},gates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Custom gate config (overrides template)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_status",description:"Get pipeline status \u2014 current stage, progress, gate config. Pass feature name for specific pipeline, or omit for all active pipelines. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name (omit to list all active pipelines)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pipeline_advance",description:"Advance pipeline past the current gate. Marks current stage as approved and moves to the next stage. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},approved_by:{type:"string",description:"Who approved this gate (default: agent)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_configure",description:"Change gate modes on an active pipeline. Use to escalate or relax gates during development. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},updates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Stage-to-gate-mode updates"},reason:{type:"string",description:"Reason for the configuration change"}},required:["feature","updates","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_escalate",description:"Flag a pipeline stage for user input. Use when a gate requires a decision the agent cannot make autonomously. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},stage:{type:"string",enum:["specify","plan","task","implement","validate"],description:"Stage to escalate"},question:{type:"string",description:"Question for the user"},options:{type:"array",items:{type:"string"},description:"Available options for the user"},context:{type:"object",description:"Additional context for the decision"}},required:["feature","stage","question","options"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_abort",description:"Cancel and archive an active pipeline. Use when a feature is abandoned or no longer needed. ~100 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_pipeline_list",description:"List all active pipelines with current stages and progress. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function zo(t,e,s){switch(t){case "paradigm_pipeline_start":{let n=e.feature,r=e.template||"add-feature",i=e.gates,o;if(i)o={specify:i.specify||"manual",plan:i.plan||"manual",task:i.task||"auto",implement:i.implement||"sentinel",validate:i.validate||"sentinel"};else {let l=Go[r];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${r}`,available:Object.keys(Go)})};o=l.gates;}let a=id(n,o,r),c=yt(s.rootDir,a);return {handled:true,text:JSON.stringify({created:true,feature:a.feature,template:r,file:c,current_stage:a.current_stage,gate_config:a.gate_config,stages:a.stages,hint:`Pipeline '${a.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let n=e.feature;if(n){let i=mt(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=te.filter(a=>i.stages[a].status==="approved").length;return {handled:true,text:JSON.stringify({feature:i.feature,created:i.created,template:i.template,current_stage:i.current_stage,progress:`${o}/${te.length}`,gate_config:i.gate_config,stages:i.stages},null,2)}}let r=Jo(s.rootDir);return r.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines. Use paradigm_pipeline_start to create one."})}:{handled:true,text:JSON.stringify({count:r.length,pipelines:r.map(i=>{let o=te.filter(a=>i.stages[a].status==="approved").length;return {feature:i.feature,current_stage:i.current_stage,progress:`${o}/${te.length}`,template:i.template,created:i.created}})},null,2)}}case "paradigm_pipeline_advance":{let n=e.feature,r=e.approved_by||"agent",i=mt(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=i.current_stage,a=i.gate_config[o],c=od(o);return i.stages[o].status="approved",i.stages[o].approved_by=r,i.stages[o].approved_at=new Date().toISOString(),a==="auto"&&(i.stages[o].auto_passed_at=new Date().toISOString()),c?(i.current_stage=c,i.stages[c].status="in-progress",yt(s.rootDir,i),{handled:true,text:JSON.stringify({advanced:true,from:o,to:c,gate_mode:a,approved_by:r,pipeline:{feature:i.feature,current_stage:i.current_stage,stages:i.stages}},null,2)}):(yt(s.rootDir,i),Uo(s.rootDir,i),{handled:true,text:JSON.stringify({completed:true,feature:i.feature,message:`Pipeline '${i.feature}' completed and archived.`,stages:i.stages},null,2)})}case "paradigm_pipeline_configure":{let n=e.feature,r=e.updates,i=e.reason,o=mt(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let a=[];for(let[c,l]of Object.entries(r))if(te.includes(c)&&["auto","manual","sentinel"].includes(l)){let d=o.gate_config[c];o.gate_config[c]=l,a.push({stage:c,from:d,to:l});}return a.length===0?{handled:true,text:JSON.stringify({error:"No valid gate updates provided",valid_stages:te,valid_modes:["auto","manual","sentinel"]})}:(yt(s.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:a,reason:i,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let n=e.feature,r=e.stage,i=e.question,o=e.options,a=e.context,c=mt(s.rootDir,n);return c?(c.stages[r].status="blocked",c.stages[r].block_reason=i,yt(s.rootDir,c),{handled:true,text:JSON.stringify({escalated:true,feature:c.feature,stage:r,question:i,options:o,context:a||{},current_gate:c.gate_config[r],instruction:"This pipeline stage requires user input. Present the question and options to the user, then use paradigm_pipeline_advance or paradigm_pipeline_configure based on their response."},null,2)}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_abort":{let n=e.feature,r=mt(s.rootDir,n);return r?(Uo(s.rootDir,r),{handled:true,text:JSON.stringify({aborted:true,feature:r.feature,message:`Pipeline '${r.feature}' aborted and archived.`})}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_list":{let n=Jo(s.rootDir);return n.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:n.length,pipelines:n.map(r=>{let i=te.filter(o=>r.stages[o].status==="approved").length;return {feature:r.feature,current_stage:r.current_stage,progress:`${i}/${te.length}`,template:r.template,created:r.created}})},null,2)}}default:return {handled:false,text:""}}}b$1();var ad=$.join(Ni.homedir(),".conductor"),We=$.join(ad,"sessions");function Vo(){A.existsSync(We)||A.mkdirSync(We,{recursive:true});}function sr(t){Vo();let e={...t,registeredAt:new Date().toISOString()},s=$.join(We,`${t.pid}.json`);return A.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function Kt(t){let e=$.join(We,`${t}.json`);return A.existsSync(e)?(A.unlinkSync(e),true):false}function ir(){Vo();let t=A.readdirSync(We).filter(s=>s.endsWith(".json")),e=[];for(let s of t)try{let n=A.readFileSync($.join(We,s),"utf-8"),r=JSON.parse(n);e.push(r);}catch{}return e}function Yo(){let t=ir(),e=0;for(let s of t)cd(s.pid)||(Kt(s.pid),e++);return e}function cd(t){try{return process.kill(t,0),!0}catch{return false}}function or(){try{return execSync(`osascript -e '
102
+ ... (truncated)`:a}catch{return null}}function Co(){return [{name:"paradigm_task_create",description:"Create a task (persistent scratch-pad item that survives context windows). Returns the created task ID. ~100 tokens.",inputSchema:{type:"object",properties:{blurb:{type:"string",description:"One-line task description"},priority:{type:"string",enum:["high","medium","low"],description:"Priority level (default: medium)"},tags:{type:"array",items:{type:"string"},description:"Tags \u2014 symbols (#component), freeform labels, etc."},related_lore:{type:"array",items:{type:"string"},description:"Linked lore entry IDs"},claimant:{type:"object",description:"Owner of this task (v7 DAG). kind: archetype|human|peer; ref: role id / git user / agentId",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},parentTaskId:{type:"string",description:"Parent task id (v7 DAG edge)"},dependsOn:{type:"array",items:{type:"string"},description:"Task ids this task depends on (v7 DAG edges)"},stage:{type:"number",description:"Orchestration stage index (v7 DAG)"},external_ref:{type:"object",description:"External anchor (renamed from session_link). kind: github|session|symphony|orchestration|url",properties:{kind:{type:"string",enum:["github","session","symphony","orchestration","url"]},ref:{type:"string"}}},session_link:{type:"string",description:"(Deprecated \u2014 use external_ref) Legacy external anchor; aliased to external_ref"}},required:["blurb"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_list",description:"List/filter tasks by status, priority, tags, or symbols. Returns task list sorted by priority then date. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["open","in-progress","done","shelved","active","all"],description:"Filter by status (default: open). 'active' = open \u222A in-progress"},priority:{type:"string",enum:["high","medium","low"],description:"Filter by priority"},tag:{type:"string",description:"Filter by tag (symbol or freeform)"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_task_update",description:"Update a task (blurb, priority, status, tags). Returns updated task. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Task ID (e.g., "T-2026-02-26-001")'},blurb:{type:"string",description:"New description"},priority:{type:"string",enum:["high","medium","low"]},status:{type:"string",enum:["open","in-progress","done","shelved"]},tags:{type:"array",items:{type:"string"},description:"Replace tags"},related_lore:{type:"array",items:{type:"string"},description:"Related lore entry IDs (includes former assessment entries)"},related_assessments:{type:"array",items:{type:"string"},description:"(Deprecated \u2014 use related_lore) Alias for related_lore"},claimant:{type:"object",description:"Owner of this task (v7 DAG). kind: archetype|human|peer; ref: role id / git user / agentId",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},parentTaskId:{type:"string",description:"Parent task id (v7 DAG edge)"},dependsOn:{type:"array",items:{type:"string"},description:"Task ids this task depends on (v7 DAG edges)"},stage:{type:"number",description:"Orchestration stage index (v7 DAG)"},external_ref:{type:"object",description:"External anchor (renamed from session_link). kind: github|session|symphony|orchestration|url",properties:{kind:{type:"string",enum:["github","session","symphony","orchestration","url"]},ref:{type:"string"}}},session_link:{type:"string",description:"(Deprecated \u2014 use external_ref) Legacy external anchor; aliased to external_ref"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_done",description:"Mark a task as done. Shorthand for update with status=done. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_shelve",description:"Shelve a task (not now, not never). Shorthand for update with status=shelved. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Ro(t,e,s){switch(t){case "paradigm_task_create":{let n=await e$4(s.rootDir,{blurb:e.blurb,priority:e.priority,tags:e.tags,related_lore:e.related_lore,claimant:e.claimant,parentTaskId:e.parentTaskId,dependsOn:e.dependsOn,stage:e.stage,external_ref:e.external_ref,session_link:e.session_link}),r=await d$4(s.rootDir,n);return {handled:true,text:JSON.stringify({created:n,task:r},null,2)}}case "paradigm_task_list":{let n=await c$4(s.rootDir,{status:e.status||"open",priority:e.priority,tag:e.tag,limit:e.limit||20}),r=e.status||"open",i=[`${n.length} ${r} task(s):`];for(let o of n){let a=o.tags.length>0?` [${o.tags.join(", ")}]`:"";i.push(` [${o.priority}] ${o.id}: ${o.blurb}${a}`);}return {handled:true,text:i.join(`
103
+ `)}}case "paradigm_task_update":{let n=e.id,r={};if(e.blurb!==void 0&&(r.blurb=e.blurb),e.priority!==void 0&&(r.priority=e.priority),e.status!==void 0&&(r.status=e.status),e.tags!==void 0&&(r.tags=e.tags),e.related_lore!==void 0&&(r.related_lore=e.related_lore),e.related_assessments!==void 0&&(r.related_assessments=e.related_assessments),e.claimant!==void 0&&(r.claimant=e.claimant),e.parentTaskId!==void 0&&(r.parentTaskId=e.parentTaskId),e.dependsOn!==void 0&&(r.dependsOn=e.dependsOn),e.stage!==void 0&&(r.stage=e.stage),e.external_ref!==void 0&&(r.external_ref=e.external_ref),e.session_link!==void 0&&e.external_ref===void 0){let a=e.session_link,c=a.toLowerCase(),l=c.includes("github")?"github":c.includes("session")?"session":"url";r.external_ref={kind:l,ref:a};}if(!await f$2(s.rootDir,n,r))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let o=await d$4(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,task:o},null,2)}}case "paradigm_task_done":{let n=e.id;if(!await g$1(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let i=await d$4(s.rootDir,n);return {handled:true,text:JSON.stringify({completed:n,task:i,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let n=e.id;if(!await h$2(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let i=await d$4(s.rootDir,n);return {handled:true,text:JSON.stringify({shelved:n,task:i},null,2)}}default:return {handled:false,text:""}}}var To=0;function Po(){let t=new Date().toISOString().slice(0,10);return To++,`run_${t}_${String(To).padStart(3,"0")}`}var jo=/\{\{([^}]+)\}\}/g;function Me(t,e){if(typeof t=="string")return t.replace(jo,(s,n)=>{let r=Yl(n.trim(),e);return r!==void 0?String(r):s});if(Array.isArray(t))return t.map(s=>Me(s,e));if(t&&typeof t=="object"){let s={};for(let[n,r]of Object.entries(t))s[n]=Me(r,e);return s}return t}function Yl(t,e){let[s,...n]=t.split("."),r=n.join(".");switch(s){case "fixtures":return e.fixtures[r];case "produces":return Qn(e.produces,r);case "context":case "parent":return e.context[r];case "env":return e.env[r]??process.env[r];default:return}}function Qn(t,e){let s=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let r of s){if(n==null||typeof n!="object")return;n=n[r];}return n}function Kl(t,e){let s={};for(let[n,r]of Object.entries(t)){let i=r.match(/\{\{response\.(.+)\}\}/);if(i){let o=i[1],a=Qn(e,o);a!==void 0&&(s[n]=a);}}return s}function Xl(t,e){if(e.status!==t.status)return {pass:false,failure:`Status mismatch: expected ${t.status}, got ${e.status}`};if(t.body){let s=e.body;if(t.body.has){for(let n of t.body.has)if(s===null||typeof s!="object"||!(n in s))return {pass:false,failure:`Expected body to have key "${n}"`}}if(t.body.match)for(let[n,r]of Object.entries(t.body.match)){let i=Qn(s,n);if(JSON.stringify(i)!==JSON.stringify(r))return {pass:false,failure:`Body mismatch at "${n}": expected ${JSON.stringify(r)}, got ${JSON.stringify(i)}`}}}return {pass:true}}async function Ql(t,e,s){let n=Date.now(),r=t.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!r)return {id:t.id,status:"fail",route:t.route,gates:t.gates,failure:`Invalid route format: ${t.route}`,duration_ms:Date.now()-n};let i=r[1],o=r[2],a=Me(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...t.headers?Me(t.headers,s):{}},d=t.payload?Me(t.payload,s):void 0,u={url:c,method:i,headers:t.headers?l:void 0,payload:d};if(e.dryRun)return {id:t.id,status:"pass",route:t.route,gates:t.gates,request:u,produced:t.produces?Object.fromEntries(Object.keys(t.produces).map(p=>[p,`<dry-run:${p}>`])):void 0,duration_ms:Date.now()-n};try{let p={method:i,headers:l};d&&["POST","PUT","PATCH"].includes(i)&&(p.body=JSON.stringify(d));let g=await fetch(c,p),m;(g.headers.get("content-type")||"").includes("application/json")?m=await g.json():m=await g.text();let f={status:g.status,body:m},v=Xl(t.expect,f),h;t.produces&&v.pass&&(h=Kl(t.produces,m));let b;return (g.status===401||g.status===403)&&(b=t.gates[t.gates.length-1]),{id:t.id,status:v.pass?"pass":"fail",route:t.route,gates:t.gates,request:u,response:f,produced:h,expected_status:v.pass?void 0:t.expect.status,failure:v.failure,gate_that_blocked:b,duration_ms:Date.now()-n}}catch(p){return {id:t.id,status:"fail",route:t.route,gates:t.gates,request:u,failure:`Request failed: ${p.message}`,duration_ms:Date.now()-n}}}async function Oo(t,e,s){let n=Date.now(),r=await c$5(t,e);return r?Ao(t,r,s):{persona:e,run_id:Po(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-n}}async function Ao(t,e,s){let n=Date.now(),r=s.stopOnFailure!==false,i={fixtures:e.fixtures||{},produces:{},context:s.context||{},env:process.env},o=[],a=[],c=[],l=false;for(let y of e.journey){if(l&&r){if(o.push({id:y.id,status:"skip",route:y.route,gates:y.gates,duration_ms:0}),y.spawns)for(let v of y.spawns)c.push(v.persona);continue}let f=await Ql(y,s,i);if(o.push(f),f.status==="pass"){if(f.produced&&Object.assign(i.produces,f.produced),y.spawns)for(let v of y.spawns)a.push(v.persona);}else if(l=true,y.spawns)for(let v of y.spawns)c.push(v.persona);}let d=o.filter(y=>y.status==="pass").length,u=o.filter(y=>y.status==="fail").length,p=e.journey.length,g=o.find(y=>y.status==="fail"),m;return u===0?m=`${d}/${p} passed. All steps succeeded.`:m=`${d}/${p} passed. Failed at step ${o.indexOf(g)+1} (${g.id}): ${g.failure}`,{persona:e.id,run_id:Po(),status:u>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-n}}async function Io(t,e,s){let n=Date.now(),r=await import('fs'),i=await import('path'),o=await import('js-yaml'),a=i.join(t,".paradigm","personas","chains",`${e}.yaml`);if(!r.existsSync(a))return {chain_id:e,status:"error",persona_results:[],summary:`Chain ${e} not found`,duration_ms:Date.now()-n};let c=o.load(r.readFileSync(a,"utf8")),l;if(s.permutation&&c.permutations&&(l=c.permutations.find(y=>y.id===s.permutation),!l))return {chain_id:e,status:"error",persona_results:[],summary:`Permutation ${s.permutation} not found in chain ${e}`,duration_ms:Date.now()-n};let d=[],u={},p=s.stopOnFailure!==false;for(let y of c.order){let f=await c$5(t,y.persona);if(!f){if(d.push({persona:y.persona,status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${y.persona} not found`,duration_ms:0}),p)break;continue}if(l&&l.overrides[y.persona]){let w=l.overrides[y.persona];if(w.traits&&(f.traits={...f.traits,...w.traits}),w.journey)for(let[x,k]of Object.entries(w.journey)){let _=f.journey.find(P=>P.id===x);_&&(k.payload&&(_.payload={..._.payload,...k.payload}),k.expect&&(_.expect={..._.expect,...k.expect}));}}let v={};if(y.wait_for){let[w,x]=y.wait_for.split("."),k=d.find(P=>P.persona===w);if(k){let P=k.steps.find(C=>C.id===x);P?.produced&&(v=Object.fromEntries(Object.entries(P.produced).map(([C,j])=>[C,String(j)])));}let _=await c$5(t,w);if(_){let P=_.journey.find(C=>C.id===x);if(P?.spawns){let C=P.spawns.find(j=>j.persona===y.persona);if(C?.context){let j=u[w]||{};for(let[O,R]of Object.entries(C.context))v[O]=String(Me(R,{fixtures:{},produces:j,context:{},env:process.env}));}}}}let h=await Ao(t,f,{...s,context:v});d.push(h);let b={};for(let w of h.steps)w.produced&&Object.assign(b,w.produced);if(u[y.persona]=b,h.status==="fail"&&p)break}let g=d.filter(y=>y.status==="pass").length,m=c.order.length;return {chain_id:e,status:d.some(y=>y.status!=="pass")?"fail":"pass",persona_results:d,summary:`${g}/${m} personas passed.`,duration_ms:Date.now()-n}}function Do(t){let e=[],s=new Set;for(let n of t.journey){let i=JSON.stringify(n).match(jo)||[];for(let o of i){let a=o.replace("{{","").replace("}}","").trim(),[c,...l]=a.split("."),d=l.join(".");switch(c){case "fixtures":!t.fixtures||d in t.fixtures;break;case "produces":s.has(d)||e.push({step:n.id,template:o,error:`{{produces.${d}}} used but not produced by a prior step`});break;case "context":case "parent":break;case "env":break;case "response":break;default:e.push({step:n.id,template:o,error:`Unknown namespace "${c}" in ${o}`});}}if(n.produces)for(let o of Object.keys(n.produces))s.add(o);}return {valid:e.length===0,errors:e}}var Ho="paradigm-personas",Zl={id:Ho,version:"1.0",name:"Paradigm Personas",description:"Events from persona journey and chain execution",scope:{key:"persona_id",label:"Persona"},eventTypes:{"persona.run.start":{category:"lifecycle",severity:"info"},"persona.step.pass":{category:"assertion",severity:"info"},"persona.step.fail":{category:"assertion",severity:"warning"},"persona.step.skip":{category:"lifecycle",severity:"info"},"persona.run.complete":{category:"lifecycle",severity:"info"},"persona.chain.complete":{category:"lifecycle",severity:"info"},"persona.coverage.report":{category:"analysis",severity:"info"}}},Zn=false;async function $o(t){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!Zn)try{s.registerSchema(Zl),Zn=!0;}catch{Zn=!0;}let n=[];if("persona"in t){let r=t;n.push({type:"persona.run.start",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,total_steps:r.steps.length}});for(let i of r.steps){let o=i.status==="pass"?"persona.step.complete":`persona.step.${i.status}`;n.push({type:o,timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,step_id:i.id,route:i.route,gates:i.gates,gates_traversed:i.gates,status:i.response?.status,body:i.response?.body,signals_fired:[],duration_ms:i.duration_ms,failure:i.failure,gate_that_blocked:i.gate_that_blocked,produced_keys:i.produced?Object.keys(i.produced):[]}});}n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,status:r.status,total_steps:r.steps.length,passed:r.steps.filter(i=>i.status==="pass").length,failed:r.steps.filter(i=>i.status==="fail").length,skipped:r.steps.filter(i=>i.status==="skip").length,duration_ms:r.duration_ms,spawns_triggered:r.spawns_triggered,spawns_blocked:r.spawns_blocked}});}else {let r=t;for(let i of r.persona_results)n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,chain_id:r.chain_id,status:i.status,total_steps:i.steps.length,passed:i.steps.filter(o=>o.status==="pass").length,failed:i.steps.filter(o=>o.status==="fail").length,duration_ms:i.duration_ms}});n.push({type:"persona.chain.complete",timestamp:new Date().toISOString(),data:{chain_id:r.chain_id,status:r.status,personas_run:r.persona_results.length,personas_passed:r.persona_results.filter(i=>i.status==="pass").length,duration_ms:r.duration_ms}});}n.length>0&&s.insertEventBatch(Ho,"paradigm-personas",n);}catch{}}function Fo(){return [{name:"paradigm_persona_create",description:"Create a persona \u2014 named test actor with traits, trigger, fixtures, and journey steps. Writes a .persona file. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Persona ID (kebab-case, e.g., "alice-admin")'},name:{type:"string",description:'Human-readable name (e.g., "Agency Owner (Annual Billing)")'},description:{type:"string",description:"What this persona represents"},traits:{type:"object",description:"Key-value actor attributes (tier, billing, role, etc.)"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"],description:"How this persona enters the system"},spawned_by:{type:"string",description:"persona-id.step-id (required if type != root)"},context:{type:"object",description:"Data passed from parent spawn"}},required:["type"]},fixtures:{type:"object",description:"Test data for this persona (email, password, API keys, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering"},journey:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case)"},description:{type:"string"},route:{type:"string",description:'METHOD /path (e.g., "POST /api/auth/signup")'},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object",description:"Request body. Supports {{produces.X}} and {{fixtures.X}} interpolation."},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object",properties:{has:{type:"array",items:{type:"string"}},match:{type:"object"}}}},required:["status"]},produces:{type:"object",description:"Values to extract from response for later steps"},spawns:{type:"array",items:{type:"object",properties:{persona:{type:"string"},via:{type:"string"},context:{type:"object"}},required:["persona","via"]}},signals:{type:"array",items:{type:"string"},description:"!signal references expected to fire"}},required:["id","route","gates","expect"]}}},required:["id","name","trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_get",description:"Get full persona detail \u2014 journey, traits, spawn chain, validation status. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_list",description:"List personas with optional filters \u2014 tag, trigger type, gate, flow. ~200 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:"Filter by tag"},trigger_type:{type:"string",enum:["root","invitation","signup","api"],description:"Filter by trigger type"},gate:{type:"string",description:"Filter by gate (show personas that traverse this gate)"},flow:{type:"string",description:"Filter by flow (show personas that exercise this flow)"},limit:{type:"number",description:"Maximum results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_update",description:"Update persona fields \u2014 traits, fixtures, journey steps, tags. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"},name:{type:"string"},description:{type:"string"},traits:{type:"object"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"]},spawned_by:{type:"string"},context:{type:"object"}}},fixtures:{type:"object"},tags:{type:"array",items:{type:"string"}},journey:{type:"array",description:"Replace entire journey. Use paradigm_persona_add_step for surgical edits."}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_delete",description:"Delete a persona. Warns if other personas spawn from it. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_add_step",description:"Add a journey step to a persona. Validates gates, route format, and produce/consume chains. ~150 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case, unique within persona)"},description:{type:"string"},route:{type:"string",description:"METHOD /path"},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object"},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object"}},required:["status"]},produces:{type:"object"},spawns:{type:"array"},signals:{type:"array",items:{type:"string"}}},required:["id","route","gates","expect"]},after:{type:"string",description:"Insert after this step ID. Omit to append."}},required:["persona_id","step"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_remove_step",description:"Remove a journey step. Warns if it produces data consumed by later steps or spawns other personas. ~100 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step_id:{type:"string",description:"Step ID to remove"}},required:["persona_id","step_id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_validate",description:"Full persona validation \u2014 schema + cross-refs + Sentinel event matching with exact assertion results. Compares expected journey outcomes against actual Sentinel events. ~300 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Validate one persona. Omit for all."},deep:{type:"boolean",description:"Include cross-reference and coverage analysis (default: false)"},sentinel:{type:"boolean",description:"Compare against Sentinel events (default: true when available)"},run_id:{type:"string",description:"Validate against a specific run. Omit for latest."},chain_id:{type:"string",description:"Validate against a specific chain execution."},environment:{type:"string",description:"Filter Sentinel events by environment (dev, staging, prod, ci)."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_coverage",description:"Coverage report \u2014 which routes/gates/flows have persona coverage, which don't. Compares against portal.yaml. ~250 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_affected",description:"Given a symbol (^gate, $flow, route), return affected personas and their steps. Used by ripple. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to check (e.g., "^authenticated", "$checkout-flow", "POST /api/orders")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_run",description:"Execute a persona journey or chain against a running server. Interpolates templates, sends requests step-by-step, validates responses. Supports dry-run mode. ~500 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Run a single persona journey"},chain_id:{type:"string",description:"Run a named chain (overrides persona_id)"},base_url:{type:"string",description:'Server base URL (e.g., "http://localhost:3000")'},dry_run:{type:"boolean",description:"Validate and interpolate without making requests (default: false)"},stop_on_failure:{type:"boolean",description:"Stop on first failing step (default: true)"},permutation:{type:"string",description:"Permutation ID from chain definition"}},required:["base_url"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function No(t,e,s){switch(t){case "paradigm_persona_create":try{let n=await d$5(s.rootDir,{id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags,journey:e.journey}),r=await c$5(s.rootDir,n);return {handled:!0,text:JSON.stringify({created:n,persona:r},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_get":{let n=e.id,r=await c$5(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let i$1=await i(s.rootDir,r);return {handled:true,text:JSON.stringify({persona:r,validation:i$1},null,2)}}case "paradigm_persona_list":{let n=await b$8(s.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),r=n.map(i=>({id:i.id,name:i.name,trigger:i.trigger.type,steps:i.journey.length,gates:[...new Set(i.journey.flatMap(o=>o.gates))],tags:i.tags||[]}));return {handled:true,text:JSON.stringify({count:n.length,personas:r},null,2)}}case "paradigm_persona_update":{let n=e.id,r={};if(e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),e.traits!==void 0&&(r.traits=e.traits),e.trigger!==void 0&&(r.trigger=e.trigger),e.fixtures!==void 0&&(r.fixtures=e.fixtures),e.tags!==void 0&&(r.tags=e.tags),e.journey!==void 0&&(r.journey=e.journey),!await e$5(s.rootDir,n,r))return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let o=await c$5(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,persona:o},null,2)}}case "paradigm_persona_delete":{let n=e.id,r=await f$3(s.rootDir,n);return r.deleted?{handled:true,text:JSON.stringify({deleted:n,warnings:r.warnings,hint:r.warnings.length>0?"Other personas reference this one. Update or delete them to avoid broken spawn chains.":void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Persona ${n} not found`})}}case "paradigm_persona_add_step":try{if(!await g$2(s.rootDir,e.persona_id,e.step,e.after))return {handled:!0,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let r=await c$5(s.rootDir,e.persona_id);return {handled:!0,text:JSON.stringify({added:e.step.id,persona_id:e.persona_id,total_steps:r?.journey.length},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_remove_step":{let n=await h$3(s.rootDir,e.persona_id,e.step_id);return n.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:n.warnings},null,2)}:{handled:true,text:JSON.stringify({error:`Step ${e.step_id} not found in persona ${e.persona_id}`})}}case "paradigm_persona_validate":{let n=e.deep??false,r=e.sentinel??true,i$1={run_id:e.run_id,chain_id:e.chain_id,environment:e.environment};if(e.persona_id){let d=await c$5(s.rootDir,e.persona_id);if(!d)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let u=await i(s.rootDir,d,n);if(r)try{let p=await m$2(d,i$1);u.sentinel_assertions=p,(p.summary.failed>0||p.summary.unmatched>0)&&(u.valid=!1);}catch{}return {handled:true,text:JSON.stringify(u,null,2)}}let o=await b$8(s.rootDir),a=await Promise.all(o.map(async d=>{let u=await i(s.rootDir,d,n);if(r)try{let p=await m$2(d,i$1);u.sentinel_assertions=p,(p.summary.failed>0||p.summary.unmatched>0)&&(u.valid=!1);}catch{}return u})),c=a.filter(d=>d.valid).length,l=a.filter(d=>!d.valid).length;return {handled:true,text:JSON.stringify({total:a.length,valid:c,invalid:l,results:a.filter(d=>!d.valid||d.warnings.length>0||d.sentinel_assertions)},null,2)}}case "paradigm_persona_coverage":{let n=await k$2(s.rootDir);return {handled:true,text:JSON.stringify(n,null,2)}}case "paradigm_persona_affected":{let n=e.symbol,r=await l$2(s.rootDir,n);return r.length===0?{handled:true,text:JSON.stringify({symbol:n,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:n,affected:r},null,2)}}case "paradigm_persona_run":{let n=e.base_url,r=e.dry_run??false,i=e.stop_on_failure??true;if(e.chain_id){let o=await Io(s.rootDir,e.chain_id,{baseUrl:n,dryRun:r,stopOnFailure:i,permutation:e.permutation});return r||await $o(o),{handled:true,text:JSON.stringify(o,null,2)}}if(e.persona_id){let o=await c$5(s.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let a=Do(o);if(!a.valid&&!r)return {handled:true,text:JSON.stringify({error:"Template interpolation errors \u2014 fix before running",errors:a.errors,hint:"Use dry_run: true to see interpolated values without executing requests"},null,2)};let c=await Oo(s.rootDir,e.persona_id,{baseUrl:n,dryRun:r,stopOnFailure:i});return r||await $o(c),{handled:true,text:JSON.stringify(c,null,2)}}return {handled:true,text:JSON.stringify({error:"Either persona_id or chain_id is required"})}}default:return {handled:false,text:""}}}var ed=".paradigm/graphs",nr={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},er=200,tr=60,Ge=20,Vt=40,Eo=50,td=60;function Lo(){return [{name:"paradigm_graph_generate",description:"Generate a named GraphState JSON file for the Paradigm Symbol Graph UI. Writes to .paradigm/graphs/{name}.graph.json. View saved graphs with `paradigm graph` CLI. Returns a summary with node/edge counts and file path. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Graph name (kebab-case). Used as filename: {name}.graph.json. E.g. "auth-flow", "full-project", "checkout-subsystem".'},symbols:{type:"array",items:{type:"string"},description:'Symbol names to include (e.g. ["#auth-middleware", "^authenticated"]). Omit to include all from scan-index.'},groups:{type:"array",items:{type:"object",properties:{label:{type:"string",description:"Group display label"},symbols:{type:"array",items:{type:"string"},description:"Symbol names belonging to this group"}},required:["label","symbols"]},description:"Optional groupings of symbols."},links:{type:"array",items:{type:"object",properties:{source:{type:"string",description:"Source group label"},target:{type:"string",description:"Target group label"},label:{type:"string",description:"Edge label"}},required:["source","target"]},description:"Edges between groups (by label name)."}},required:["name"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Mo(t,e,s){if(t!=="paradigm_graph_generate")return {handled:false,text:""};try{let n=e.name||"untitled",r=n.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),i=sd(s.rootDir,e.symbols,e.groups,e.links,n),o=JSON.stringify(i,null,2),a=$.join(s.rootDir,ed);I.existsSync(a)||I.mkdirSync(a,{recursive:!0});let c=$.join(a,`${r}.graph.json`);I.writeFileSync(c,o,"utf8");let l=JSON.stringify({file:c,name:n,slug:r,nodes:i.nodes.length,edges:i.edges.length,size:`${(o.length/1024).toFixed(1)} KB`,hint:"Graph saved. Run `paradigm graph` to view in browser."},null,2);return O(l.length,t),{handled:!0,text:l}}catch(n){let r=JSON.stringify({error:n.message},null,2);return O(r.length,t),{handled:true,text:r}}}var nd={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function rd(t){let e=$.join(t,".paradigm","scan-index.json");if(!I.existsSync(e))return [];let s=JSON.parse(I.readFileSync(e,"utf8")),n=[];for(let[r,i]of Object.entries(nd)){let o=s[r];if(!(!o||typeof o!="object"))for(let[a,c]of Object.entries(o)){let l=c;n.push({id:a,name:a,category:i,prefix:nr[i]||"#",description:l.description,path:l.path,tags:l.tags});}}return n}function qo(t,e){let s=t.replace(/^[#$^!~]/,"");return e.find(n=>n.id===s||n.name===s||n.id===t||n.name===t)}function sd(t,e,s,n,r="Generated Graph"){let i=rd(t),o;e&&e.length>0?o=e.map(g=>qo(g,i)).filter(Boolean):o=i;let a=[],c=[],l=new Map,d=new Set,u=0;if(s&&s.length>0)for(let g of s){let m=`group-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;l.set(g.label,m);let y=g.symbols.map(k=>qo(k,o)).filter(Boolean),f=Math.ceil(Math.sqrt(y.length)),v=Math.ceil(y.length/f);for(let k=0;k<y.length;k++){let _=y[k],P=k%f,C=Math.floor(k/f),j=nr[_.category]||"#";a.push({id:`sym-${_.id}`,type:"symbolNode",position:{x:Vt+P*(er+Ge),y:Eo+Vt+C*(tr+Ge)},parentId:m,data:{type:"symbol",symbol:_,label:`${j}${_.name}`}}),d.add(_.id);}let h=Math.max(f,1),b=Math.max(v,1),w=Vt*2+h*er+(h-1)*Ge,x=Eo+Vt*2+b*tr+(b-1)*Ge;a.unshift({id:m,type:"groupNode",position:{x:u,y:0},style:{width:w,height:x},data:{type:"group",label:g.label}}),u+=w+td;}let p=o.filter(g=>!d.has(g.id));if(p.length>0){let g=s&&s.length>0?400:0,m=Math.ceil(Math.sqrt(p.length));for(let y=0;y<p.length;y++){let f=p[y],v=y%m,h=Math.floor(y/m),b=nr[f.category]||"#";a.push({id:`sym-${f.id}`,type:"symbolNode",position:{x:v*(er+Ge),y:g+h*(tr+Ge)},data:{type:"symbol",symbol:f,label:`${b}${f.name}`}});}}if(n&&n.length>0)for(let g of n){let m=l.get(g.source),y=l.get(g.target);m&&y&&c.push({id:`e-${m}-${y}`,source:m,target:y,type:"default",label:g.label,data:{label:g.label}});}return {version:"1.0",name:r,projectId:$.basename(t),lastModified:new Date().toISOString(),nodes:a,edges:c}}var te=["specify","plan","task","implement","validate"],ht=".paradigm/pipeline",Go={"add-feature":{gates:{specify:"manual",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Standard feature addition with manual spec/plan review"},"bug-fix":{gates:{specify:"auto",plan:"auto",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Quick bug fix with automated gates except validation"},"security-change":{gates:{specify:"manual",plan:"manual",task:"manual",implement:"manual",validate:"manual"},description:"Security-sensitive change with all-manual gates"},refactor:{gates:{specify:"auto",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Code refactoring with manual plan review"}};function Yt(t){return t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function mt(t,e){let s=Yt(e),n=$.join(t,ht,`${s}.yaml`);return I.existsSync(n)?qe.load(I.readFileSync(n,"utf8")):null}function yt(t,e){let s=Yt(e.feature),n=$.join(t,ht);I.existsSync(n)||I.mkdirSync(n,{recursive:true});let r=$.join(n,`${s}.yaml`);return I.writeFileSync(r,qe.dump(e,{lineWidth:120}),"utf8"),r}function Jo(t){let e=$.join(t,ht);return I.existsSync(e)?I.readdirSync(e).filter(s=>s.endsWith(".yaml")&&!s.startsWith("completed")).map(s=>{try{return qe.load(I.readFileSync($.join(e,s),"utf8"))}catch{return null}}).filter(Boolean):[]}function id(t,e,s){let n={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return n.specify.status="in-progress",{version:"1.0",feature:Yt(t),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:s,stages:n}}function od(t){let e=te.indexOf(t);return e<te.length-1?te[e+1]:null}function Uo(t,e){let s=Yt(e.feature),n=$.join(t,ht,"completed");I.existsSync(n)||I.mkdirSync(n,{recursive:true});let r=$.join(n,`${s}.yaml`);I.writeFileSync(r,qe.dump(e,{lineWidth:120}),"utf8");let i=$.join(t,ht,`${s}.yaml`);I.existsSync(i)&&I.unlinkSync(i);}function Wo(){return [{name:"paradigm_pipeline_start",description:"Create a new spec pipeline for a feature. Uses templates (add-feature, bug-fix, security-change, refactor) or custom gate config. Returns pipeline state. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name or description (will be slugified)"},template:{type:"string",enum:["add-feature","bug-fix","security-change","refactor"],description:"Pipeline template (default: add-feature)"},gates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Custom gate config (overrides template)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_status",description:"Get pipeline status \u2014 current stage, progress, gate config. Pass feature name for specific pipeline, or omit for all active pipelines. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name (omit to list all active pipelines)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pipeline_advance",description:"Advance pipeline past the current gate. Marks current stage as approved and moves to the next stage. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},approved_by:{type:"string",description:"Who approved this gate (default: agent)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_configure",description:"Change gate modes on an active pipeline. Use to escalate or relax gates during development. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},updates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Stage-to-gate-mode updates"},reason:{type:"string",description:"Reason for the configuration change"}},required:["feature","updates","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_escalate",description:"Flag a pipeline stage for user input. Use when a gate requires a decision the agent cannot make autonomously. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},stage:{type:"string",enum:["specify","plan","task","implement","validate"],description:"Stage to escalate"},question:{type:"string",description:"Question for the user"},options:{type:"array",items:{type:"string"},description:"Available options for the user"},context:{type:"object",description:"Additional context for the decision"}},required:["feature","stage","question","options"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_abort",description:"Cancel and archive an active pipeline. Use when a feature is abandoned or no longer needed. ~100 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_pipeline_list",description:"List all active pipelines with current stages and progress. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function zo(t,e,s){switch(t){case "paradigm_pipeline_start":{let n=e.feature,r=e.template||"add-feature",i=e.gates,o;if(i)o={specify:i.specify||"manual",plan:i.plan||"manual",task:i.task||"auto",implement:i.implement||"sentinel",validate:i.validate||"sentinel"};else {let l=Go[r];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${r}`,available:Object.keys(Go)})};o=l.gates;}let a=id(n,o,r),c=yt(s.rootDir,a);return {handled:true,text:JSON.stringify({created:true,feature:a.feature,template:r,file:c,current_stage:a.current_stage,gate_config:a.gate_config,stages:a.stages,hint:`Pipeline '${a.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let n=e.feature;if(n){let i=mt(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=te.filter(a=>i.stages[a].status==="approved").length;return {handled:true,text:JSON.stringify({feature:i.feature,created:i.created,template:i.template,current_stage:i.current_stage,progress:`${o}/${te.length}`,gate_config:i.gate_config,stages:i.stages},null,2)}}let r=Jo(s.rootDir);return r.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines. Use paradigm_pipeline_start to create one."})}:{handled:true,text:JSON.stringify({count:r.length,pipelines:r.map(i=>{let o=te.filter(a=>i.stages[a].status==="approved").length;return {feature:i.feature,current_stage:i.current_stage,progress:`${o}/${te.length}`,template:i.template,created:i.created}})},null,2)}}case "paradigm_pipeline_advance":{let n=e.feature,r=e.approved_by||"agent",i=mt(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=i.current_stage,a=i.gate_config[o],c=od(o);return i.stages[o].status="approved",i.stages[o].approved_by=r,i.stages[o].approved_at=new Date().toISOString(),a==="auto"&&(i.stages[o].auto_passed_at=new Date().toISOString()),c?(i.current_stage=c,i.stages[c].status="in-progress",yt(s.rootDir,i),{handled:true,text:JSON.stringify({advanced:true,from:o,to:c,gate_mode:a,approved_by:r,pipeline:{feature:i.feature,current_stage:i.current_stage,stages:i.stages}},null,2)}):(yt(s.rootDir,i),Uo(s.rootDir,i),{handled:true,text:JSON.stringify({completed:true,feature:i.feature,message:`Pipeline '${i.feature}' completed and archived.`,stages:i.stages},null,2)})}case "paradigm_pipeline_configure":{let n=e.feature,r=e.updates,i=e.reason,o=mt(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let a=[];for(let[c,l]of Object.entries(r))if(te.includes(c)&&["auto","manual","sentinel"].includes(l)){let d=o.gate_config[c];o.gate_config[c]=l,a.push({stage:c,from:d,to:l});}return a.length===0?{handled:true,text:JSON.stringify({error:"No valid gate updates provided",valid_stages:te,valid_modes:["auto","manual","sentinel"]})}:(yt(s.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:a,reason:i,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let n=e.feature,r=e.stage,i=e.question,o=e.options,a=e.context,c=mt(s.rootDir,n);return c?(c.stages[r].status="blocked",c.stages[r].block_reason=i,yt(s.rootDir,c),{handled:true,text:JSON.stringify({escalated:true,feature:c.feature,stage:r,question:i,options:o,context:a||{},current_gate:c.gate_config[r],instruction:"This pipeline stage requires user input. Present the question and options to the user, then use paradigm_pipeline_advance or paradigm_pipeline_configure based on their response."},null,2)}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_abort":{let n=e.feature,r=mt(s.rootDir,n);return r?(Uo(s.rootDir,r),{handled:true,text:JSON.stringify({aborted:true,feature:r.feature,message:`Pipeline '${r.feature}' aborted and archived.`})}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_list":{let n=Jo(s.rootDir);return n.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:n.length,pipelines:n.map(r=>{let i=te.filter(o=>r.stages[o].status==="approved").length;return {feature:r.feature,current_stage:r.current_stage,progress:`${i}/${te.length}`,template:r.template,created:r.created}})},null,2)}}default:return {handled:false,text:""}}}b$1();var ad=$.join(Ni.homedir(),".conductor"),We=$.join(ad,"sessions");function Vo(){I.existsSync(We)||I.mkdirSync(We,{recursive:true});}function sr(t){Vo();let e={...t,registeredAt:new Date().toISOString()},s=$.join(We,`${t.pid}.json`);return I.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function Kt(t){let e=$.join(We,`${t}.json`);return I.existsSync(e)?(I.unlinkSync(e),true):false}function ir(){Vo();let t=I.readdirSync(We).filter(s=>s.endsWith(".json")),e=[];for(let s of t)try{let n=I.readFileSync($.join(We,s),"utf-8"),r=JSON.parse(n);e.push(r);}catch{}return e}function Yo(){let t=ir(),e=0;for(let s of t)cd(s.pid)||(Kt(s.pid),e++);return e}function cd(t){try{return process.kill(t,0),!0}catch{return false}}function or(){try{return execSync(`osascript -e '
104
104
  tell application "System Events"
105
105
  set frontApp to first application process whose frontmost is true
106
106
  return bundle identifier of frontApp
107
107
  end tell
108
- '`,{encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function ar(t){try{return execSync("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function xu(t){try{let e=process.pid,s=or(),n=ar(t),r;try{let o=execSync(`ps -o ppid= -p ${e}`,{encoding:"utf-8",timeout:3e3}).trim();r=parseInt(o,10),isNaN(r)&&(r=void 0);}catch{}sr({pid:e,parentPid:r,projectDir:t,terminal:s,branch:n});let i=()=>{try{Kt(e);}catch{}};process.on("exit",i),process.on("SIGTERM",()=>{i(),process.exit(0);}),a.component("#conductor-loader").info("Auto-registered with Conductor",{pid:e});}catch{a.component("#conductor-loader").warn("Auto-registration with Conductor skipped (non-fatal)");}}function Ko(){return [{name:"paradigm_conductor_register",description:'Register this Claude Code session with Paradigm Conductor. Makes the session visible in the Conductor overlay for voice/gesture/gaze dispatch. Call this when the user says "/conduct" or wants to surface a session to Conductor. ~100 tokens.',inputSchema:{type:"object",properties:{label:{type:"string",description:'Human-readable label for this session (e.g., "backend refactor", "auth feature")'},terminal:{type:"string",description:'Terminal bundle ID (e.g., "com.mitchellh.ghostty"). Auto-detected if omitted.'}},required:[]},annotations:{title:"Register with Conductor",readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"paradigm_conductor_unregister",description:"Unregister this Claude Code session from Paradigm Conductor. Removes it from the Conductor overlay. Call when ending a session or when the user wants to hide from Conductor. ~50 tokens.",inputSchema:{type:"object",properties:{},required:[]},annotations:{title:"Unregister from Conductor",readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"paradigm_conductor_list",description:"List all Claude Code sessions currently registered with Paradigm Conductor. Shows PIDs, project dirs, and labels. ~150 tokens.",inputSchema:{type:"object",properties:{clean:{type:"boolean",description:"If true, clean up stale sessions (dead PIDs) before listing"}},required:[]},annotations:{title:"List Conductor sessions",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}}]}async function Xo(t,e,s){switch(t){case "paradigm_conductor_register":{let n=process.pid,r=s.rootDir,i=e.terminal||or(),o=ar(r),a;try{let d=execSync(`ps -o ppid= -p ${n}`,{encoding:"utf-8",timeout:3e3}).trim();a=parseInt(d,10),isNaN(a)&&(a=void 0);}catch{}let c=sr({pid:n,parentPid:a,projectDir:r,terminal:i,label:e.label,branch:o}),l=["\u2713 Registered with Conductor","",` PID: ${c.pid}`,` Project: ${c.projectDir}`];return c.branch&&l.push(` Branch: ${c.branch}`),c.label&&l.push(` Label: ${c.label}`),c.terminal&&l.push(` Terminal: ${c.terminal}`),l.push(` File: ~/.conductor/sessions/${c.pid}.json`),l.push(""),l.push("This session is now visible in Paradigm Conductor."),l.push("Conductor will auto-discover it via the registration file."),{text:l.join(`
108
+ '`,{encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function ar(t){try{return execSync("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:3e3}).trim()||void 0}catch{return}}function Cu(t){try{let e=process.pid,s=or(),n=ar(t),r;try{let o=execSync(`ps -o ppid= -p ${e}`,{encoding:"utf-8",timeout:3e3}).trim();r=parseInt(o,10),isNaN(r)&&(r=void 0);}catch{}sr({pid:e,parentPid:r,projectDir:t,terminal:s,branch:n});let i=()=>{try{Kt(e);}catch{}};process.on("exit",i),process.on("SIGTERM",()=>{i(),process.exit(0);}),a.component("#conductor-loader").info("Auto-registered with Conductor",{pid:e});}catch{a.component("#conductor-loader").warn("Auto-registration with Conductor skipped (non-fatal)");}}function Ko(){return [{name:"paradigm_conductor_register",description:'Register this Claude Code session with Paradigm Conductor. Makes the session visible in the Conductor overlay for voice/gesture/gaze dispatch. Call this when the user says "/conduct" or wants to surface a session to Conductor. ~100 tokens.',inputSchema:{type:"object",properties:{label:{type:"string",description:'Human-readable label for this session (e.g., "backend refactor", "auth feature")'},terminal:{type:"string",description:'Terminal bundle ID (e.g., "com.mitchellh.ghostty"). Auto-detected if omitted.'}},required:[]},annotations:{title:"Register with Conductor",readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"paradigm_conductor_unregister",description:"Unregister this Claude Code session from Paradigm Conductor. Removes it from the Conductor overlay. Call when ending a session or when the user wants to hide from Conductor. ~50 tokens.",inputSchema:{type:"object",properties:{},required:[]},annotations:{title:"Unregister from Conductor",readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false}},{name:"paradigm_conductor_list",description:"List all Claude Code sessions currently registered with Paradigm Conductor. Shows PIDs, project dirs, and labels. ~150 tokens.",inputSchema:{type:"object",properties:{clean:{type:"boolean",description:"If true, clean up stale sessions (dead PIDs) before listing"}},required:[]},annotations:{title:"List Conductor sessions",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}}]}async function Xo(t,e,s){switch(t){case "paradigm_conductor_register":{let n=process.pid,r=s.rootDir,i=e.terminal||or(),o=ar(r),a;try{let d=execSync(`ps -o ppid= -p ${n}`,{encoding:"utf-8",timeout:3e3}).trim();a=parseInt(d,10),isNaN(a)&&(a=void 0);}catch{}let c=sr({pid:n,parentPid:a,projectDir:r,terminal:i,label:e.label,branch:o}),l=["\u2713 Registered with Conductor","",` PID: ${c.pid}`,` Project: ${c.projectDir}`];return c.branch&&l.push(` Branch: ${c.branch}`),c.label&&l.push(` Label: ${c.label}`),c.terminal&&l.push(` Terminal: ${c.terminal}`),l.push(` File: ~/.conductor/sessions/${c.pid}.json`),l.push(""),l.push("This session is now visible in Paradigm Conductor."),l.push("Conductor will auto-discover it via the registration file."),{text:l.join(`
109
109
  `),handled:true}}case "paradigm_conductor_unregister":{let n=process.pid;return Kt(n)?{text:`\u2713 Unregistered from Conductor (PID ${n}).
110
110
  This session is no longer visible in the Conductor overlay.`,handled:true}:{text:`Session (PID ${n}) was not registered with Conductor.`,handled:true}}case "paradigm_conductor_list":{e.clean&&Yo()>0;let n=ir();if(n.length===0)return {text:`No sessions registered with Conductor.
111
111
  Use paradigm_conductor_register or /conduct to register.`,handled:true};let r=[`${n.length} session(s) registered with Conductor:
112
112
  `];for(let i of n){let o=[` PID ${i.pid}`];i.label&&o.push(`"${i.label}"`),o.push(`\u2014 ${i.projectDir}`),i.branch&&o.push(`(${i.branch})`),r.push(o.join(" "));}return e.clean&&r.push(`
113
113
  (Stale sessions cleaned)`),{text:r.join(`
114
- `),handled:true}}default:return {text:"",handled:false}}}function Zo(){return [{name:"paradigm_symphony_peek",description:"Ultra-cheap inbox check \u2014 file stat only, no parsing. Returns { hasNew: true/false }. Use with /loop 10s for near-free monitoring. When hasNew is true, call paradigm_symphony_poll to read messages. ~15 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:"Short status blurb (same as poll). Updates heartbeat."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_poll",description:"Read inbox notes and process them. Call when paradigm_symphony_peek returns hasNew: true, or directly via /loop for continuous messaging. Returns unread notes formatted as markdown with thread context and suggested actions. Updates heartbeat and optional status blurb. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:'Short status blurb describing what you are currently working on (e.g., "Implementing auth middleware \u2014 3 files modified"). Visible to humans and other agents in the Network view.'}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_send",description:"Send a note to other agents or broadcast. Auto-creates thread if no threadRoot provided. Supports intents: question, context, proposal, decision, action, etc. ~100 tokens.",inputSchema:{type:"object",properties:{intent:{type:"string",enum:["question","context","clarification","proposal","verification","action","decision","alert","approval","rejection","reference","handoff","task","task-ack","progress","approval-request","approval-response","task-complete","task-failed"],description:"Message intent (what kind of message this is). Task protocol intents: task (assignment), task-ack, progress, approval-request, approval-response, task-complete, task-failed."},text:{type:"string",description:"Message text content"},parentId:{type:"string",description:"ID of message being replied to"},threadRoot:{type:"string",description:"Thread ID to post in (auto-created if omitted)"},recipients:{type:"array",items:{type:"string"},description:"Agent IDs to send to (omit for broadcast)"},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols referenced (e.g., ["#auth-service", "$login-flow"])'},diff:{type:"string",description:"Code diff to include with the message"},decision:{type:"string",description:"Decision text to record (for intent=decision)"}},required:["intent","text"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_status",description:"Show Symphony network status: linked agents (with awake/asleep detection), active threads, unread count, pending file requests. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_thread",description:"Get full thread context: all notes in order, participants, extracted decisions, and referenced symbols. ~200 tokens.",inputSchema:{type:"object",properties:{threadId:{type:"string",description:"Thread ID (thr-XXXXXXXX format)"},depth:{type:"number",description:"Maximum messages to return (default: 50)"}},required:["threadId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_request_file",description:"Request a file from another agent's project. Human approval required (unless auto-approved in trust config). Files matching hard-deny patterns (.env, *.key, etc.) are always blocked. ~100 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:'Relative file path to request (e.g., "src/auth/middleware.ts")'},from:{type:"string",description:'Agent ID to request file from (e.g., "backend/core")'},reason:{type:"string",description:"Why this file is needed"},snippet:{type:"string",description:'Specific function or line range needed (e.g., "validateToken function" or "lines 50-100")'}},required:["filePath","from","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_approve_file",description:'Approve or deny a pending file request. Use action "approve" to send file, "deny" to reject, or "approve-redacted" to send with secrets stripped. ~100 tokens.',inputSchema:{type:"object",properties:{requestId:{type:"string",description:"File request ID (freq-XXXXXXXX format)"},action:{type:"string",enum:["approve","deny","approve-redacted"],description:"Approve, deny, or approve with redaction"},reason:{type:"string",description:"Reason for denial (required for deny action)"}},required:["requestId","action"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ea(t,e,s){let n=n$4(s.rootDir);switch(n||(n=j$1(s.rootDir)),t){case "paradigm_symphony_peek":{let r=e.status;o$4(n.id,r);let{hasNew:i}=s$2(n.id),o=i?N("pending").length:0;return {handled:true,text:JSON.stringify(i?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{m$3(),S$1();let r=e.status;o$4(n.id,r);let i=v$2(n.id);if(i.length>0){let c=i[i.length-1].id;z$3(n.id,c),t$1(n.id);}B$1(n.id);let o=N("pending");return i.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:n.id})}:{handled:true,text:dd(i,o)}}case "paradigm_symphony_send":{let r=e.intent,i=e.text,o=e.parentId,a=e.threadRoot,c=e.recipients,l=e.symbols,d=e.diff,u=e.decision,p=false;if(!a&&!o){let f=i.length>60?i.slice(0,60)+"...":i;a=C$1(f,bt(n)).id,p=true;}let g;if(c&&c.length>0){let f=l$3();g=c.map(v=>{let h=f.find(b=>b.id===v);return h?bt(h):{id:v,name:v,type:"agent"}});}let m=I({sender:bt(n),recipients:g,intent:r,text:i,parentId:o,threadRoot:a,symbols:l,diff:d,decision:u}),y=J$1(m);if(md(m).catch(()=>{}),p&&a){({timestamp:m.timestamp,sender:m.sender,content:{text:`Thread created: ${m.content.text.slice(0,60)}`}});fetch(`${cr}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:"thread:created",category:"lifecycle",timestamp:m.timestamp,scopeValue:a,service:m.sender.project||"symphony",severity:"info",data:{topic:m.content.text.slice(0,60),initiator:m.sender.name,threadId:a}})}).catch(()=>{});}return {handled:true,text:JSON.stringify({sent:true,messageId:m.id,threadId:a,threadCreated:p,deliveredTo:y,intent:r})}}case "paradigm_symphony_status":{m$3();let r=l$3(),i=E("active"),o=v$2(n.id),a=N("pending"),c=[];try{let{loadPeers:l}=await import('./symphony-peers-U4KHMKGI.js');c=l().filter(u=>!u.revoked).map(u=>({id:u.id,address:u.address,agents:u.agents?.length??0,lastSeen:u.lastSeen}));}catch{}return {handled:true,text:JSON.stringify({identity:{id:n.id,project:n.project,role:n.role},agents:r.map(l=>({id:l.id,name:l.name,project:l.project,role:l.role,status:q$2(l)?"asleep":"awake",lastPoll:l.lastPoll,statusBlurb:l.statusBlurb})),peers:c,activeThreads:i.map(l=>({id:l.id,topic:l.topic,participants:l.participants.length,messageCount:l.messageCount,lastActivity:l.lastActivity})),unreadCount:o.length,pendingFileRequests:a.length},null,2)}}case "paradigm_symphony_thread":{let r=e.threadId,i=e.depth||50,o=D$1(r);if(!o)return {handled:true,text:JSON.stringify({error:`Thread not found: ${r}`})};let a=H$2(r).slice(0,i),c=[],l=new Set,d=new Set;for(let u of a){u.content.decision&&c.push(u.content.decision),u.intent==="decision"&&u.content.text&&c.push(u.content.text);for(let p of u.symbols)l.add(p);if(u.attachments)for(let p of u.attachments)p.type==="file"&&d.add(p.name);}return {handled:true,text:JSON.stringify({thread:{id:o.id,topic:o.topic,status:o.status,createdAt:o.createdAt,decision:o.decision},participants:o.participants,messages:a.map(u=>({id:u.id,sender:u.sender.name,intent:u.intent,text:u.content.text,timestamp:u.timestamp,symbols:u.symbols,hasDiff:!!u.content.diff,hasDecision:!!u.content.decision})),decisions:c,symbolsDiscussed:[...l],filesReferenced:[...d]},null,2)}}case "paradigm_symphony_request_file":{let r=e.filePath,i=e.from,o=e.reason,a=e.snippet,c=K();if(Q$1(r,c))return {handled:true,text:JSON.stringify({error:`File path "${r}" is on the hard-deny list and cannot be requested.`,deniedPatterns:c.defaults.neverApprove})};let l=L({filePath:r,requester:bt(n),reason:o,snippet:a,threadRoot:void 0}),d=I({sender:bt(n),recipients:[{id:i,name:i,type:"agent"}],intent:"fileRequest",text:`Requesting file: ${r}
114
+ `),handled:true}}default:return {text:"",handled:false}}}b$1();function Zo(){return [{name:"paradigm_symphony_peek",description:"Ultra-cheap inbox check \u2014 file stat only, no parsing. Returns { hasNew: true/false }. Use with /loop 10s for near-free monitoring. When hasNew is true, call paradigm_symphony_poll to read messages. ~15 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:"Short status blurb (same as poll). Updates heartbeat."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_poll",description:"Read inbox notes and process them. Call when paradigm_symphony_peek returns hasNew: true, or directly via /loop for continuous messaging. Returns unread notes formatted as markdown with thread context and suggested actions. Updates heartbeat and optional status blurb. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:'Short status blurb describing what you are currently working on (e.g., "Implementing auth middleware \u2014 3 files modified"). Visible to humans and other agents in the Network view.'}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_send",description:"Send a note to other agents or broadcast. Auto-creates thread if no threadRoot provided. Supports intents: question, context, proposal, decision, action, etc. ~100 tokens.",inputSchema:{type:"object",properties:{intent:{type:"string",enum:["question","context","clarification","proposal","verification","action","decision","alert","approval","rejection","reference","handoff","task","task-ack","progress","approval-request","approval-response","task-complete","task-failed"],description:"Message intent (what kind of message this is). Task protocol intents: task (assignment), task-ack, progress, approval-request, approval-response, task-complete, task-failed."},text:{type:"string",description:"Message text content"},parentId:{type:"string",description:"ID of message being replied to"},threadRoot:{type:"string",description:"Thread ID to post in (auto-created if omitted)"},recipients:{type:"array",items:{type:"string"},description:"Agent IDs to send to (omit for broadcast)"},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols referenced (e.g., ["#auth-service", "$login-flow"])'},diff:{type:"string",description:"Code diff to include with the message"},decision:{type:"string",description:"Decision text to record (for intent=decision)"}},required:["intent","text"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_status",description:"Show Symphony network status: linked agents (with awake/asleep detection), active threads, unread count, pending file requests. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_thread",description:"Get full thread context: all notes in order, participants, extracted decisions, and referenced symbols. ~200 tokens.",inputSchema:{type:"object",properties:{threadId:{type:"string",description:"Thread ID (thr-XXXXXXXX format)"},depth:{type:"number",description:"Maximum messages to return (default: 50)"}},required:["threadId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_request_file",description:"Request a file from another agent's project. Human approval required (unless auto-approved in trust config). Files matching hard-deny patterns (.env, *.key, etc.) are always blocked. ~100 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:'Relative file path to request (e.g., "src/auth/middleware.ts")'},from:{type:"string",description:'Agent ID to request file from (e.g., "backend/core")'},reason:{type:"string",description:"Why this file is needed"},snippet:{type:"string",description:'Specific function or line range needed (e.g., "validateToken function" or "lines 50-100")'}},required:["filePath","from","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_approve_file",description:'Approve or deny a pending file request. Use action "approve" to send file, "deny" to reject, or "approve-redacted" to send with secrets stripped. ~100 tokens.',inputSchema:{type:"object",properties:{requestId:{type:"string",description:"File request ID (freq-XXXXXXXX format)"},action:{type:"string",enum:["approve","deny","approve-redacted"],description:"Approve, deny, or approve with redaction"},reason:{type:"string",description:"Reason for denial (required for deny action)"}},required:["requestId","action"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function dd(t,e){let s={progress:"in-progress","task-complete":"done","task-failed":"shelved"};try{let{updateTask:n,completeTask:r,shelveTask:i}=await import('./task-loader-YZME4RKE.js');for(let o of t){let a$1=s[o.intent];if(!a$1)continue;let c=o.metadata?.task?.taskId;if(c)try{let l=!1;if(a$1==="done")l=await r(e,c);else if(a$1==="shelved"){if(l=await i(e,c),l){let d=o.content?.text?`peer task-failed: ${o.content.text.slice(0,200)}`:"peer reported task-failed";await n(e,c,{crash_reason:d});}}else l=await n(e,c,{status:a$1});l?a.signal("!symphony-status-flowback").info("Applied peer status flow-back to local task",{taskId:c,intent:o.intent,status:a$1}):a.signal("!symphony-status-flowback").debug("Flow-back no-op (task absent or terminal already)",{taskId:c,intent:o.intent,status:a$1});}catch(l){a.signal("!symphony-status-flowback").warn("Per-note flow-back failed (non-fatal)",{taskId:c,intent:o.intent,error:l instanceof Error?l.message:String(l)});}}}catch(n){a.signal("!symphony-status-flowback").warn("Status flow-back pass failed (non-fatal)",{error:n instanceof Error?n.message:String(n)});}}async function ea(t,e,s){let n=n$4(s.rootDir);switch(n||(n=j$2(s.rootDir)),t){case "paradigm_symphony_peek":{let r=e.status;o$4(n.id,r);let{hasNew:i}=s$2(n.id),o=i?N("pending").length:0;return {handled:true,text:JSON.stringify(i?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{m$3(),S$1();let r=e.status;o$4(n.id,r);let i=v$2(n.id);if(i.length>0){let c=i[i.length-1].id;z$3(n.id,c),t$1(n.id);}B$1(n.id),i.length>0&&await dd(i,s.rootDir);let o=N("pending");return i.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:n.id})}:{handled:true,text:pd(i,o)}}case "paradigm_symphony_send":{let r=e.intent,i=e.text,o=e.parentId,a=e.threadRoot,c=e.recipients,l=e.symbols,d=e.diff,u=e.decision,p=false;if(!a&&!o){let f=i.length>60?i.slice(0,60)+"...":i;a=C$1(f,bt(n)).id,p=true;}let g;if(c&&c.length>0){let f=l$3();g=c.map(v=>{let h=f.find(b=>b.id===v);return h?bt(h):{id:v,name:v,type:"agent"}});}let m=I$1({sender:bt(n),recipients:g,intent:r,text:i,parentId:o,threadRoot:a,symbols:l,diff:d,decision:u}),y=J$1(m);if(yd(m).catch(()=>{}),p&&a){({timestamp:m.timestamp,sender:m.sender,content:{text:`Thread created: ${m.content.text.slice(0,60)}`}});fetch(`${cr}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:"thread:created",category:"lifecycle",timestamp:m.timestamp,scopeValue:a,service:m.sender.project||"symphony",severity:"info",data:{topic:m.content.text.slice(0,60),initiator:m.sender.name,threadId:a}})}).catch(()=>{});}return {handled:true,text:JSON.stringify({sent:true,messageId:m.id,threadId:a,threadCreated:p,deliveredTo:y,intent:r})}}case "paradigm_symphony_status":{m$3();let r=l$3(),i=E("active"),o=v$2(n.id),a=N("pending"),c=[];try{let{loadPeers:l}=await import('./symphony-peers-U4KHMKGI.js');c=l().filter(u=>!u.revoked).map(u=>({id:u.id,address:u.address,agents:u.agents?.length??0,lastSeen:u.lastSeen}));}catch{}return {handled:true,text:JSON.stringify({identity:{id:n.id,project:n.project,role:n.role},agents:r.map(l=>({id:l.id,name:l.name,project:l.project,role:l.role,status:q$2(l)?"asleep":"awake",lastPoll:l.lastPoll,statusBlurb:l.statusBlurb})),peers:c,activeThreads:i.map(l=>({id:l.id,topic:l.topic,participants:l.participants.length,messageCount:l.messageCount,lastActivity:l.lastActivity})),unreadCount:o.length,pendingFileRequests:a.length},null,2)}}case "paradigm_symphony_thread":{let r=e.threadId,i=e.depth||50,o=D$1(r);if(!o)return {handled:true,text:JSON.stringify({error:`Thread not found: ${r}`})};let a=H$2(r).slice(0,i),c=[],l=new Set,d=new Set;for(let u of a){u.content.decision&&c.push(u.content.decision),u.intent==="decision"&&u.content.text&&c.push(u.content.text);for(let p of u.symbols)l.add(p);if(u.attachments)for(let p of u.attachments)p.type==="file"&&d.add(p.name);}return {handled:true,text:JSON.stringify({thread:{id:o.id,topic:o.topic,status:o.status,createdAt:o.createdAt,decision:o.decision},participants:o.participants,messages:a.map(u=>({id:u.id,sender:u.sender.name,intent:u.intent,text:u.content.text,timestamp:u.timestamp,symbols:u.symbols,hasDiff:!!u.content.diff,hasDecision:!!u.content.decision})),decisions:c,symbolsDiscussed:[...l],filesReferenced:[...d]},null,2)}}case "paradigm_symphony_request_file":{let r=e.filePath,i=e.from,o=e.reason,a=e.snippet,c=K();if(Q$1(r,c))return {handled:true,text:JSON.stringify({error:`File path "${r}" is on the hard-deny list and cannot be requested.`,deniedPatterns:c.defaults.neverApprove})};let l=L({filePath:r,requester:bt(n),reason:o,snippet:a,threadRoot:void 0}),d=I$1({sender:bt(n),recipients:[{id:i,name:i,type:"agent"}],intent:"fileRequest",text:`Requesting file: ${r}
115
115
  Reason: ${o}${a?`
116
- Snippet: ${a}`:""}`,symbols:[]});return J$1(d),{handled:true,text:JSON.stringify({requestId:l.request.requestId,status:"pending",filePath:r,from:i,message:`File request created. The owning agent's human must approve via "paradigm symphony approve ${l.request.requestId}" or "paradigm_symphony_approve_file".`})}}case "paradigm_symphony_approve_file":{let r=e.requestId,i=e.action,o=e.reason;if(i==="deny"){let l=P(r,o);return {handled:true,text:JSON.stringify({success:l,requestId:r,action:"denied",reason:o||"No reason provided"})}}let a=i==="approve-redacted",c=O$1(r,s.rootDir,a);return c.success?{handled:true,text:JSON.stringify({success:true,requestId:r,action:a?"approved-redacted":"approved",filePath:c.delivery?.filePath,size:c.delivery?.size,hash:c.delivery?.hash})}:{handled:true,text:JSON.stringify({success:false,requestId:r,error:c.error})}}default:return {handled:false,text:""}}}function bt(t){return {id:t.id,name:t.name,type:t.type||"agent",project:t.project,role:t.role}}function dd(t,e){let s=[],n=new Map;for(let r of t){let i=r.threadRoot||"direct";n.has(i)||n.set(i,[]),n.get(i).push(r);}for(let[r,i]of n){let o=r;if(r!=="direct"){let a=D$1(r);a&&(o=a.topic);}s.push(`## Symphony: ${i.length} new note${i.length!==1?"s":""} in "${o}"
117
- `);for(let a=0;a<i.length;a++){let c=i[a],l=new Date(c.timestamp).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),d=`${c.sender.name}${c.sender.project?` (${c.sender.project})`:""}`;s.push(`### ${a+1}. ${d} \u2014 ${ud(c.intent)} (${l})`),s.push(`> ${c.content.text.split(`
116
+ Snippet: ${a}`:""}`,symbols:[]});return J$1(d),{handled:true,text:JSON.stringify({requestId:l.request.requestId,status:"pending",filePath:r,from:i,message:`File request created. The owning agent's human must approve via "paradigm symphony approve ${l.request.requestId}" or "paradigm_symphony_approve_file".`})}}case "paradigm_symphony_approve_file":{let r=e.requestId,i=e.action,o=e.reason;if(i==="deny"){let l=P(r,o);return {handled:true,text:JSON.stringify({success:l,requestId:r,action:"denied",reason:o||"No reason provided"})}}let a=i==="approve-redacted",c=O$1(r,s.rootDir,a);return c.success?{handled:true,text:JSON.stringify({success:true,requestId:r,action:a?"approved-redacted":"approved",filePath:c.delivery?.filePath,size:c.delivery?.size,hash:c.delivery?.hash})}:{handled:true,text:JSON.stringify({success:false,requestId:r,error:c.error})}}default:return {handled:false,text:""}}}function bt(t){return {id:t.id,name:t.name,type:t.type||"agent",project:t.project,role:t.role}}function pd(t,e){let s=[],n=new Map;for(let r of t){let i=r.threadRoot||"direct";n.has(i)||n.set(i,[]),n.get(i).push(r);}for(let[r,i]of n){let o=r;if(r!=="direct"){let a=D$1(r);a&&(o=a.topic);}s.push(`## Symphony: ${i.length} new note${i.length!==1?"s":""} in "${o}"
117
+ `);for(let a=0;a<i.length;a++){let c=i[a],l=new Date(c.timestamp).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),d=`${c.sender.name}${c.sender.project?` (${c.sender.project})`:""}`;s.push(`### ${a+1}. ${d} \u2014 ${gd(c.intent)} (${l})`),s.push(`> ${c.content.text.split(`
118
118
  `).join(`
119
119
  > `)}`),c.symbols.length>0&&s.push(`> Symbols: ${c.symbols.join(", ")}`),c.content.diff&&s.push(`
120
120
  \`\`\`diff
121
121
  ${c.content.diff}
122
122
  \`\`\``),c.content.decision&&s.push(`
123
- **Decision:** ${c.content.decision}`);let u=pd(c);u&&s.push(`
123
+ **Decision:** ${c.content.decision}`);let u=ud(c);u&&s.push(`
124
124
  **Suggested action:** ${u}`),s.push("");}}if(e.length>0){s.push(`## Pending File Requests (${e.length})
125
125
  `);for(let r of e)s.push(`- **${r.request.filePath}** from ${r.request.requester.name}: ${r.request.reason}`),s.push(` Approve: \`paradigm_symphony_approve_file({ requestId: "${r.request.requestId}", action: "approve" })\``);s.push("");}return s.join(`
126
- `)}function pd(t){switch(t.intent){case "question":return 'Reply with paradigm_symphony_send using intent "context" or "clarification"';case "proposal":return 'Reply with intent "approval" or "rejection"';case "fileRequest":return "Use paradigm_symphony_approve_file to approve or deny";case "handoff":return "Review handoff context and continue the work";case "alert":return 'Investigate the alert and reply with intent "action"';case "verification":return 'Confirm with intent "approval" or clarify with "clarification"';default:return null}}function ud(t){return t.charAt(0).toUpperCase()+t.slice(1)}var cr="http://localhost:3838",Qo=false;function gd(t){switch(t){case "question":return "note:question";case "context":return "note:context";case "clarification":return "note:clarification";case "proposal":return "note:proposal";case "verification":return "note:verification";case "action":return "note:action";case "decision":return "note:decision";case "alert":return "note:alert";case "approval":return "note:approval";case "rejection":return "note:rejection";case "reference":return "note:reference";case "handoff":return "note:handoff";case "fileRequest":return "file:requested";case "fileApproved":return "file:approved";case "fileDenied":return "file:denied";case "fileDelivery":return "file:delivered";default:return "note:context"}}function fd(t){if(t.startsWith("note:")){let e=t.split(":")[1];if(["question","context","clarification","verification","reference"].includes(e))return "dialogue";if(["proposal","action"].includes(e))return "action";if(["decision","approval","rejection"].includes(e))return "outcome";if(e==="alert")return "system";if(e==="handoff")return "lifecycle"}return t.startsWith("thread:")||t.startsWith("participant:")?"lifecycle":t.startsWith("file:")?"transfer":"dialogue"}async function md(t){try{Qo||(await fetch(`${cr}/api/schemas`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:"paradigm-symphony",version:"1.0.0",name:"Symphony Conversations",description:"Agent-to-agent messaging events from The Score protocol"})}).catch(()=>{}),Qo=!0);let e=gd(t.intent),s=fd(e);await fetch(`${cr}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:e,category:s,timestamp:t.timestamp,scopeValue:t.threadRoot||t.id,service:t.sender.project||"symphony",severity:s==="system"?"error":s==="outcome"?"warn":"info",parentEventId:t.parentId,data:{sender:t.sender.name,senderRole:t.sender.role||"core",text:t.content.text,symbols:t.symbols,diff:t.content.diff,decision:t.content.decision,parentId:t.parentId,threadId:t.threadRoot}})});}catch{}}b$1();var ta=/^[a-z0-9][a-z0-9-]{0,63}$/,lr=["track","index","chronological","featured"],dr=64,yd=z$1.object({id:z$1.string().regex(ta,"invalid section id"),name:z$1.string().min(1).max(120),order:z$1.number().int().min(0).max(9999),style:z$1.enum(lr,{errorMap:()=>({message:`section.style must be one of ${lr.join("|")}`})}),description:z$1.string().max(1e3).optional(),default:z$1.boolean({invalid_type_error:"section.default must be a boolean"}).optional()}).strict(),pr=z$1.array(yd).max(dr,`sections must contain \u2264${dr} entries`);z$1.object({sections:pr.optional()}).passthrough();z$1.object({section:z$1.string().regex(ta).optional(),order:z$1.number().int().min(0).max(9999).optional()}).passthrough();var ra="@a-company/university",sa=".paradigm/university",ia=".paradigm/cache/packs.json",J=class extends Error{constructor(s,n){super(`pack-load failed (${s}: ${n})`);this.errorClass=s;this.detail=n;this.name="PackLoadError";}},hd=["id","name","version","schema_version","tenant_kind"],bd=new Set(["first-party","project","external"]),na={id:"main",name:"Curriculum",order:1,style:"track",default:true};function vd(t){if(t==null)return [{...na}];if(Array.isArray(t)&&t.length===0)return [{...na}];let e=pr.safeParse(t);if(!e.success){let i=e.error.issues[0],o=i?`${i.path.join(".")||"sections"}: ${i.message}`:"sections failed schema validation";throw new J("manifest-invalid",o)}let s=e.data.map(i=>({...i})),n=new Set;for(let i of s){if(n.has(i.id))throw new J("manifest-invalid",`duplicate section id "${i.id}"`);n.add(i.id);}s.length===1&&!s[0].default&&(s[0]={...s[0],default:true});let r=s.filter(i=>i.default===true);if(r.length>1)throw new J("manifest-invalid",`at most one section may set default: true (found ${r.length})`);return s.sort((i,o)=>i.order-o.order||i.id.localeCompare(o.id)),s}function Xt(t){let e=$.join(t,o$5),s=Et(e);switch(s.status){case "missing":throw new J("missing-manifest",`no ${o$5} at pack root`);case "unparseable":throw new J("manifest-unparseable",s.detail);case "invalid":throw new J("manifest-invalid",s.detail);case "ok":{let n=s.data;if(!n||typeof n!="object")throw new J("manifest-invalid","manifest is not an object");for(let r of hd){let i=n[r];if(i==null||i==="")throw new J("missing-required-field",`required field ${String(r)} is missing or empty`)}if(!bd.has(String(n.tenant_kind)))throw new J("missing-required-field","tenant_kind must be one of first-party|project|external");return n.sections=vd(n.sections),n}}}function ur(t){let e=_d(t);if(e)return e;let s=[],n=$.join(t,"node_modules",ra);if(A.existsSync($.join(n,o$5)))try{let i=Xt(n);s.push({manifest:i,rootDir:n,source:"first-party"});}catch(i){a.component("#pack-loader").warn("first-party pack manifest invalid",{errorClass:i instanceof J?i.errorClass:"other"});}for(let i of wd(t))try{let o=Xt(i);s.push({manifest:o,rootDir:i,source:"npm"});}catch(o){a.component("#pack-loader").warn("npm pack manifest invalid",{errorClass:o instanceof J?o.errorClass:"other"});}let r=$.join(t,sa);if(A.existsSync(r)&&A.statSync(r).isDirectory()){let i=$.join(r,o$5),o;if(A.existsSync(i))try{o=Xt(r),s.push({manifest:o,rootDir:r,source:"local"});}catch(c){a.component("#pack-loader").warn("local pack manifest invalid",{errorClass:c instanceof J?c.errorClass:"other"});}let a$1=o?.id??"project";for(let c of kd(r))try{let l=Xt(c);s.push({manifest:l,rootDir:c,source:"local",parentPackId:a$1});}catch(l){a.component("#pack-loader").warn("discipline sub-pack manifest invalid",{errorClass:l instanceof J?l.errorClass:"other"});}}return Sd(t,s),s}function wd(t){let e=$.join(t,"package.json");if(!A.existsSync(e))return [];let s;try{s=JSON.parse(A.readFileSync(e,"utf8"));}catch{return []}let n=new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{}),...Object.keys(s.peerDependencies||{})]);if(n.size===0)return [];let r=$.join(t,"node_modules");if(!A.existsSync(r))return [];let i=[];for(let o of n){if(o===ra)continue;let a=$.join(r,o,"package.json");if(!A.existsSync(a))continue;let c;try{c=JSON.parse(A.readFileSync(a,"utf8"));}catch{continue}let l=c.paradigm?.universityPack;if(typeof l!="string"||l.length===0)continue;let d=$.resolve($.dirname(a),l);A.existsSync($.join(d,o$5))&&i.push(d);}return i}function kd(t){let e=[],s;try{s=A.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let n of s){if(!n.isDirectory()||n.name.startsWith("."))continue;let r=$.join(t,n.name);A.existsSync($.join(r,o$5))&&e.push(r);}return e}function Qt(t,e){if(typeof t!="string"||t.length===0)throw new Error("resolveEntryAddress: address must be a non-empty string");let s=t.indexOf(":");if(s!==-1){let r=t.slice(0,s),i=t.slice(s+1);if(!r||!i)throw new Error("resolveEntryAddress: malformed <pack-id>:<entry-id> address");return {packId:r,entryId:i}}let n=t;if(e.candidatePacks&&e.entryExistsIn){let r=e.candidatePacks.filter(i=>e.entryExistsIn(i,n));if(r.length>1){let i=r.map(o=>`${o}:${n}`).join(", ");throw new Error(`resolveEntryAddress: bare entry id "${n}" is ambiguous across packs. Candidates: ${i}`)}if(r.length===1)return {packId:r[0],entryId:n}}return {packId:e.activePack,entryId:n}}function oa(t){try{return A.statSync($.join(t,"node_modules")).mtime.getTime()}catch{return}}function aa(t){try{return A.statSync($.join(t,sa)).mtime.getTime()}catch{return}}function _d(t){let e=$.join(t,ia);if(!A.existsSync(e))return null;let s;try{s=JSON.parse(A.readFileSync(e,"utf8"));}catch{return null}if(s.version!==1||!Array.isArray(s.packs))return null;let n=oa(t),r=aa(t);return s.node_modules_mtime_ms!==n||s.local_university_mtime_ms!==r?null:s.packs.map(i=>({manifest:i.manifest,rootDir:i.rootDir,source:i.source,...i.parentPackId?{parentPackId:i.parentPackId}:{}}))}function Sd(t,e){let s=$.join(t,ia);try{A.mkdirSync($.dirname(s),{recursive:!0});let n={version:1,node_modules_mtime_ms:oa(t),local_university_mtime_ms:aa(t),packs:e.map(r=>({manifest:r.manifest,rootDir:r.rootDir,source:r.source,...r.parentPackId?{parentPackId:r.parentPackId}:{}}))};A.writeFileSync(s,JSON.stringify(n,null,2),"utf8");}catch{}}function ca(){let t=process.env.PARADIGM_AUTHOR;if(t)return gr(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return gr(e)}catch{}try{let e=Ni.userInfo().username;if(e)return gr(e)}catch{}return "unknown"}function gr(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function la(){return new Date().toISOString().slice(0,10)}function Be(t,e){let s=[];try{s=ur(t);}catch{}if(e){let c=s.find(l=>l.manifest.id===e);if(c)return {packId:c.manifest.id,packRoot:c.rootDir,packs:s}}let n=s.find(c=>c.manifest.tenant_kind==="project");if(n)return {packId:n.manifest.id,packRoot:n.rootDir,packs:s};let r=s.find(c=>c.manifest.tenant_kind==="first-party");if(r)return {packId:r.manifest.id,packRoot:r.rootDir,packs:s};let i=q$3(t);return {packId:r$2(i)?.id??"project",packRoot:i,packs:s}}var Cd=$.join(".paradigm","university");function Ve(t,e){return $.resolve(e)===$.resolve(t,Cd)}function pa(){return [{name:"paradigm_university_search",description:"Search university content by type, tag, difficulty, or symbol. v6.0: result ids are <pack-id>:<entry-id> (minor-breaking). ~150 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Filter by content type"},tag:{type:"string",description:"Filter by tag prefix"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Filter by difficulty level"},symbol:{type:"string",description:'Filter by Paradigm symbol (e.g., "#api-gateway")'},query:{type:"string",description:"Free-text search in title and tags"},category:{type:"string",description:'Filter by category ID (e.g., "paradigm-core", "extracurricular")'},track:{type:"string",enum:["core","extracurricular"],description:"Filter by track"},pack:{type:"string",description:"v6.0: target a specific content pack by id (default: project pack if present, else first-party)"},section:{type:"string",description:"v6.5: filter by section id (within the active pack)"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_get",description:"Fetch a content item by ID. Accepts bare id or <pack-id>:<entry-id>. Returns full content (body for notes/policies, questions for quizzes). ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID: bare (N-foo) or qualified (paradigm:N-foo)"},pack:{type:"string",description:"v6.0: disambiguate a bare id against a specific pack (optional)"}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_create",description:"Create a new university content item (note, policy, quiz, or path). v6.0: honors optional pack selector. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Content type to create"},title:{type:"string",description:"Content title"},body:{type:"string",description:"Markdown body for notes/policies. Quiz/path YAML content for those types."},tags:{type:"array",items:{type:"string"},description:"Tags for classification"},symbols:{type:"array",items:{type:"string"},description:"Paradigm symbols referenced by this content"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Difficulty level (default: beginner)"},estimatedMinutes:{type:"number",description:"Estimated reading/completion time in minutes"},prerequisites:{type:"array",items:{type:"string"},description:"IDs of prerequisite content items"},category:{type:"string",description:"Category ID for the content (default: project defaultCategory)"},pack:{type:"string",description:"v6.0: target a specific pack by id (default: project pack)"},passThreshold:{type:"number",description:"For quizzes: pass threshold 0.0-1.0 (default: 0.7)"},questions:{type:"array",description:"For quizzes: array of {id, question, choices: {A:..., B:...}, correct, explanation?}"},ordered:{type:"boolean",description:"For learning paths: whether steps must be completed in order"},steps:{type:"array",description:"For learning paths: array of {content, required, passRequired?, note?}"}},required:["type","title"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_update",description:"Update an existing content item. id accepts bare or <pack-id>:<entry-id>. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to update (bare or qualified)"},pack:{type:"string",description:"v6.0: disambiguate a bare id against a specific pack (optional)"},title:{type:"string",description:"New title"},body:{type:"string",description:"New body content"},tags:{type:"array",items:{type:"string"},description:"New tags"},symbols:{type:"array",items:{type:"string"},description:"New symbols"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"]},estimatedMinutes:{type:"number"},category:{type:"string",description:"Category ID for the content"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_onboard",description:"Get recommended onboarding sequence. v6.0: honors optional pack selector. ~200 tokens.",inputSchema:{type:"object",properties:{student:{type:"string",description:"Student name to check completion (auto-resolved if omitted)"},pack:{type:"string",description:"v6.0: target a specific pack (default: project pack)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_validate",description:"Validate content integrity. v6.0: honors optional pack selector. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to validate (bare or qualified; validates all if omitted)"},pack:{type:"string",description:"v6.0: target a specific pack (default: all packs)"},deep:{type:"boolean",description:"Enable deep cross-reference checks against scan-index (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_pack_list",description:"v6.0: List discovered content packs with manifest metadata. ~200 tokens.",inputSchema:{type:"object",properties:{tenant_kind:{type:"string",enum:["first-party","project","external"],description:"Filter by tenant kind"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ua(t,e,s){if(t==="paradigm_university_pack_list"){let n=e.tenant_kind,r=[];try{r=ur(s.rootDir);}catch{r=[];}let o={packs:(n?r.filter(c=>c.manifest.tenant_kind===n):r).map(c=>{let l=(c.manifest.sections??[]).slice().sort((d,u)=>d.order-u.order||d.id.localeCompare(u.id));return {id:c.manifest.id,name:c.manifest.name,version:c.manifest.version,tenant_kind:c.manifest.tenant_kind,...c.manifest.disciplines&&c.manifest.disciplines.length>0?{discipline:c.manifest.disciplines[0]}:{},entry_count:A$3(c.rootDir),sections:l,path:c.rootDir}})},a=JSON.stringify(o,null,2);return O(a.length,t),{handled:true,text:a}}if(t==="paradigm_university_search"){let n=e.pack,{packId:r,packRoot:i}=Be(s.rootDir,n),a=r$2(i)?.sections?.find(p=>p.default===true)?.id??"main",{entries:c,total:l,returned:d}=z$4(s.rootDir,{type:e.type,tag:e.tag,difficulty:e.difficulty,symbol:e.symbol,query:e.query,category:e.category,track:e.track,section:e.section,limit:e.limit},n?i:void 0),u=JSON.stringify({count:c.length,total:l,returned:d,truncated:l>d,pack:r,results:c.map(p=>({id:`${r}:${p.id}`,title:p.title,type:p.type,difficulty:p.difficulty,tags:p.tags,symbols:p.symbols,section:p.section??a,...typeof p.order=="number"?{order:p.order}:{}}))},null,2);return O(u.length,t),{handled:true,text:u}}if(t==="paradigm_university_get"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let r=e.pack,{packId:i,packRoot:o}=Be(s.rootDir,r),a;try{a=Qt(n,{activePack:i}).entryId;}catch{a=n;}let c=t$2(s.rootDir,a,o);if(c){let p=JSON.stringify({id:c.frontmatter.id,title:c.frontmatter.title,type:c.frontmatter.type,author:c.frontmatter.author,created:c.frontmatter.created,updated:c.frontmatter.updated,tags:c.frontmatter.tags,symbols:c.frontmatter.symbols,difficulty:c.frontmatter.difficulty,prerequisites:c.frontmatter.prerequisites,body:c.body},null,2);return O(p.length,t),{handled:true,text:p}}let l=v$3(s.rootDir,a,o);if(l){let p=JSON.stringify(l,null,2);return O(p.length,t),{handled:true,text:p}}let d=x$1(s.rootDir,a,o);if(d){let p=JSON.stringify(d,null,2);return O(p.length,t),{handled:true,text:p}}let u=JSON.stringify({error:`Content "${n}" not found`});return O(u.length,t),{handled:true,text:u}}if(t==="paradigm_university_create"){let n=e.type,r=e.title;if(!n||!r)return {handled:true,text:JSON.stringify({error:"type and title are required"})};let i=e.pack,{packRoot:o}=Be(s.rootDir,i),a=ca(),c=la(),l=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40);if(n==="quiz"){let y=`Q-${l}`,f={id:y,title:r,description:e.body||"",author:a,created:c,updated:c,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,passThreshold:e.passThreshold??.7,questions:e.questions||[],...e.category?{category:e.category}:{}};w(s.rootDir,f,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let v=JSON.stringify({created:y,type:"quiz",file:`content/quizzes/${y}.yaml`},null,2);return O(v.length,t),{handled:true,text:v}}if(n==="path"){let y=`LP-${l}`,f={id:y,title:r,description:e.body||"",author:a,created:c,updated:c,tags:e.tags||[],ordered:e.ordered??true,steps:e.steps||[],...e.category?{category:e.category}:{}};y$1(s.rootDir,f,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let v=JSON.stringify({created:y,type:"path",file:`content/paths/${y}.yaml`},null,2);return O(v.length,t),{handled:true,text:v}}let u=`${n==="policy"?"P":"N"}-${l}`,p={id:u,title:r,type:n,author:a,created:c,updated:c,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,prerequisites:e.prerequisites||[],...e.category?{category:e.category}:{}};u$1(s.rootDir,p,e.body||"",o),Ve(s.rootDir,o)&&B$2(s.rootDir);let m=JSON.stringify({created:u,type:n,file:`content/${n==="policy"?"policies":"notes"}/${u}.md`},null,2);return O(m.length,t),{handled:true,text:m}}if(t==="paradigm_university_update"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let r=e.pack,{packId:i,packRoot:o}=Be(s.rootDir,r),a;try{a=Qt(n,{activePack:i}).entryId;}catch{a=n;}let c=la(),l=t$2(s.rootDir,a,o);if(l){let g={...l.frontmatter};e.title&&(g.title=e.title),e.tags&&(g.tags=e.tags),e.symbols&&(g.symbols=e.symbols),e.difficulty&&(g.difficulty=e.difficulty),e.estimatedMinutes!==void 0&&(g.estimatedMinutes=e.estimatedMinutes),e.category!==void 0&&(g.category=e.category),g.updated=c;let m=e.body??l.body;u$1(s.rootDir,g,m,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let y=JSON.stringify({updated:a,type:g.type},null,2);return O(y.length,t),{handled:true,text:y}}let d=v$3(s.rootDir,a,o);if(d){e.title&&(d.title=e.title),e.tags&&(d.tags=e.tags),e.symbols&&(d.symbols=e.symbols),e.difficulty&&(d.difficulty=e.difficulty),e.category!==void 0&&(d.category=e.category),d.updated=c,w(s.rootDir,d,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let g=JSON.stringify({updated:a,type:"quiz"},null,2);return O(g.length,t),{handled:true,text:g}}let u=x$1(s.rootDir,a,o);if(u){e.title&&(u.title=e.title),e.tags&&(u.tags=e.tags),e.category!==void 0&&(u.category=e.category),u.updated=c,y$1(s.rootDir,u,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let g=JSON.stringify({updated:a,type:"path"},null,2);return O(g.length,t),{handled:true,text:g}}let p=JSON.stringify({error:`Content "${n}" not found`});return O(p.length,t),{handled:true,text:p}}if(t==="paradigm_university_onboard"){let n=e.student||ca(),r=e.pack,{packId:i,packRoot:o}=Be(s.rootDir,r),a=s$3(s.rootDir).branding.name;if(r){let d=r$2(o);d?.name&&(a=d.name);}let c=E$1(s.rootDir,n,r?o:void 0),l=JSON.stringify({university:a,pack:i,student:n,...c},null,2);return O(l.length,t),{handled:true,text:l}}if(t==="paradigm_university_validate"){let n=e.pack,{packId:r,packRoot:i}=Be(s.rootDir,n),o=e.id,a=o;if(o)try{a=Qt(o,{activePack:r}).entryId;}catch{}let c=C$2(s.rootDir,{id:a,deep:e.deep},n?i:void 0),l=JSON.stringify({pack:r,...c},null,2);return O(l.length,t),{handled:true,text:l}}return {handled:false,text:""}}function Rd(t){try{let e=$.join(t,".paradigm","config.yaml");if(A.existsSync(e)){let n=qe.load(A.readFileSync(e,"utf-8")).platform;if(n?.port&&typeof n.port=="number")return n.port}}catch{}return 3850}function Pd(t){try{let e=$.join(t,".paradigm","config.yaml");if(A.existsSync(e)){let s=qe.load(A.readFileSync(e,"utf-8")),n=s.project||$.basename(t),r=s.role||"core";return `${n}/${r}`}}catch{}return `${$.basename(t)}/core`}async function Xe(t,e,s){let n=Rd(t),r=Pd(t),i=`http://localhost:${n}/api/platform/agent-command`;try{let o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,agentId:r,payload:s}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let c=await o.text();return {ok:!1,error:`HTTP ${o.status}: ${c}`}}return {ok:!0,data:await o.json()}}catch(o){return {ok:false,error:`Platform server unreachable (${o instanceof Error?o.message:String(o)}). Is \`paradigm serve\` running?`}}}function ga(){return [{name:"paradigm_platform_navigate",description:"Navigate the Platform UI to a section, select a symbol, or open a lore entry. The browser updates in real-time. If the user is actively interacting, shows a prompt instead of auto-navigating. ~100 tokens.",inputSchema:{type:"object",properties:{section:{type:"string",enum:["overview","lore","graph","sentinel","university","symphony"],description:"Section to navigate to"},symbol:{type:"string",description:'Symbol to select (e.g., "#payment-service")'},loreId:{type:"string",description:"Lore entry ID to open in lore section"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_highlight",description:"Temporarily highlight symbols in the Platform UI with a pulsing glow. Auto-expires after duration. Use to draw attention to specific components during explanations. ~100 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbol IDs to highlight (e.g., ["#payment-service", "#api-gateway"])'},color:{type:"string",description:"Highlight color (CSS color, defaults to agent color)"},duration:{type:"number",description:"Duration in milliseconds (default: 5000)"},pulse:{type:"boolean",description:"Whether to pulse the highlight (default: true)"},label:{type:"string",description:"Optional label shown near highlighted symbols"}},required:["symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_annotate",description:"Show a toast notification, callout on a graph node, or badge in the Platform UI. Use for communicating decisions, warnings, or context to the user visually. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["toast","callout","badge"],description:"Annotation type: toast (notification), callout (floating note on graph node), badge (icon on symbol)"},message:{type:"string",description:"Annotation message text"},symbol:{type:"string",description:"Symbol to attach callout/badge to (required for callout/badge)"},severity:{type:"string",enum:["info","warning","error","success"],description:"Visual severity (default: info)"},duration:{type:"number",description:"Auto-dismiss duration in milliseconds (default: 6000, 0 = persistent)"}},required:["type","message"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_observe",description:"Read the current Platform UI state: what section the user is viewing, what symbol is selected, theme, connected agents, and active highlights/annotations. ~150 tokens.",inputSchema:{type:"object",properties:{detail:{type:"string",enum:["summary","full"],description:"Level of detail (default: summary)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_platform_clear",description:"Remove agent highlights, annotations, or all agent effects from the Platform UI. ~50 tokens.",inputSchema:{type:"object",properties:{target:{type:"string",enum:["highlights","annotations","all"],description:"What to clear (default: all)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function fa(t,e,s){switch(t){case "paradigm_platform_navigate":{let n=await Xe(s.projectDir,"navigate",{section:e.section,symbol:e.symbol,loreId:e.loreId});if(!n.ok)return {handled:true,text:`**Navigate failed:** ${n.error}`};let r=n.data;if(r.navigated){let i=[];r.section&&i.push(`section: **${r.section}**`),r.symbol&&i.push(`symbol: **${r.symbol}**`);let o=r.userActive?" (user was active \u2014 shown as prompt)":"";return {handled:true,text:`Navigated to ${i.join(", ")}${o}`}}return {handled:true,text:`Navigation skipped: ${r.reason}`}}case "paradigm_platform_highlight":{let n=await Xe(s.projectDir,"highlight",{symbols:e.symbols,color:e.color,duration:e.duration,pulse:e.pulse,label:e.label});if(!n.ok)return {handled:true,text:`**Highlight failed:** ${n.error}`};let r=n.data;return r.highlighted?{handled:true,text:`Highlighted **${r.count}** symbol(s)${e.label?` with label "${e.label}"`:""}`}:{handled:true,text:`Highlight skipped: ${r.reason}`}}case "paradigm_platform_annotate":{let n=await Xe(s.projectDir,"annotate",{type:e.type,message:e.message,symbol:e.symbol,severity:e.severity,duration:e.duration});if(!n.ok)return {handled:true,text:`**Annotate failed:** ${n.error}`};let r=n.data;return r.annotated?{handled:true,text:`Created ${e.type} annotation: "${e.message}"`}:{handled:true,text:`Annotation skipped: ${r.reason}`}}case "paradigm_platform_observe":{let n=await Xe(s.projectDir,"observe",{detail:e.detail});if(!n.ok)return {handled:true,text:`**Observe failed:** ${n.error}`};let r=n.data,i=r.state,o=[`## Platform UI State
126
+ `)}function ud(t){switch(t.intent){case "question":return 'Reply with paradigm_symphony_send using intent "context" or "clarification"';case "proposal":return 'Reply with intent "approval" or "rejection"';case "fileRequest":return "Use paradigm_symphony_approve_file to approve or deny";case "handoff":return "Review handoff context and continue the work";case "alert":return 'Investigate the alert and reply with intent "action"';case "verification":return 'Confirm with intent "approval" or clarify with "clarification"';default:return null}}function gd(t){return t.charAt(0).toUpperCase()+t.slice(1)}var cr="http://localhost:3838",Qo=false;function fd(t){switch(t){case "question":return "note:question";case "context":return "note:context";case "clarification":return "note:clarification";case "proposal":return "note:proposal";case "verification":return "note:verification";case "action":return "note:action";case "decision":return "note:decision";case "alert":return "note:alert";case "approval":return "note:approval";case "rejection":return "note:rejection";case "reference":return "note:reference";case "handoff":return "note:handoff";case "fileRequest":return "file:requested";case "fileApproved":return "file:approved";case "fileDenied":return "file:denied";case "fileDelivery":return "file:delivered";default:return "note:context"}}function md(t){if(t.startsWith("note:")){let e=t.split(":")[1];if(["question","context","clarification","verification","reference"].includes(e))return "dialogue";if(["proposal","action"].includes(e))return "action";if(["decision","approval","rejection"].includes(e))return "outcome";if(e==="alert")return "system";if(e==="handoff")return "lifecycle"}return t.startsWith("thread:")||t.startsWith("participant:")?"lifecycle":t.startsWith("file:")?"transfer":"dialogue"}async function yd(t){try{Qo||(await fetch(`${cr}/api/schemas`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:"paradigm-symphony",version:"1.0.0",name:"Symphony Conversations",description:"Agent-to-agent messaging events from The Score protocol"})}).catch(()=>{}),Qo=!0);let e=fd(t.intent),s=md(e);await fetch(`${cr}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:e,category:s,timestamp:t.timestamp,scopeValue:t.threadRoot||t.id,service:t.sender.project||"symphony",severity:s==="system"?"error":s==="outcome"?"warn":"info",parentEventId:t.parentId,data:{sender:t.sender.name,senderRole:t.sender.role||"core",text:t.content.text,symbols:t.symbols,diff:t.content.diff,decision:t.content.decision,parentId:t.parentId,threadId:t.threadRoot}})});}catch{}}b$1();var ta=/^[a-z0-9][a-z0-9-]{0,63}$/,lr=["track","index","chronological","featured"],dr=64,hd=z$1.object({id:z$1.string().regex(ta,"invalid section id"),name:z$1.string().min(1).max(120),order:z$1.number().int().min(0).max(9999),style:z$1.enum(lr,{errorMap:()=>({message:`section.style must be one of ${lr.join("|")}`})}),description:z$1.string().max(1e3).optional(),default:z$1.boolean({invalid_type_error:"section.default must be a boolean"}).optional()}).strict(),pr=z$1.array(hd).max(dr,`sections must contain \u2264${dr} entries`);z$1.object({sections:pr.optional()}).passthrough();z$1.object({section:z$1.string().regex(ta).optional(),order:z$1.number().int().min(0).max(9999).optional()}).passthrough();var ra="@a-company/university",sa=".paradigm/university",ia=".paradigm/cache/packs.json",J=class extends Error{constructor(s,n){super(`pack-load failed (${s}: ${n})`);this.errorClass=s;this.detail=n;this.name="PackLoadError";}},bd=["id","name","version","schema_version","tenant_kind"],vd=new Set(["first-party","project","external"]),na={id:"main",name:"Curriculum",order:1,style:"track",default:true};function wd(t){if(t==null)return [{...na}];if(Array.isArray(t)&&t.length===0)return [{...na}];let e=pr.safeParse(t);if(!e.success){let i=e.error.issues[0],o=i?`${i.path.join(".")||"sections"}: ${i.message}`:"sections failed schema validation";throw new J("manifest-invalid",o)}let s=e.data.map(i=>({...i})),n=new Set;for(let i of s){if(n.has(i.id))throw new J("manifest-invalid",`duplicate section id "${i.id}"`);n.add(i.id);}s.length===1&&!s[0].default&&(s[0]={...s[0],default:true});let r=s.filter(i=>i.default===true);if(r.length>1)throw new J("manifest-invalid",`at most one section may set default: true (found ${r.length})`);return s.sort((i,o)=>i.order-o.order||i.id.localeCompare(o.id)),s}function Xt(t){let e=$.join(t,o$5),s=Et(e);switch(s.status){case "missing":throw new J("missing-manifest",`no ${o$5} at pack root`);case "unparseable":throw new J("manifest-unparseable",s.detail);case "invalid":throw new J("manifest-invalid",s.detail);case "ok":{let n=s.data;if(!n||typeof n!="object")throw new J("manifest-invalid","manifest is not an object");for(let r of bd){let i=n[r];if(i==null||i==="")throw new J("missing-required-field",`required field ${String(r)} is missing or empty`)}if(!vd.has(String(n.tenant_kind)))throw new J("missing-required-field","tenant_kind must be one of first-party|project|external");return n.sections=wd(n.sections),n}}}function ur(t){let e=Sd(t);if(e)return e;let s=[],n=$.join(t,"node_modules",ra);if(I.existsSync($.join(n,o$5)))try{let i=Xt(n);s.push({manifest:i,rootDir:n,source:"first-party"});}catch(i){a.component("#pack-loader").warn("first-party pack manifest invalid",{errorClass:i instanceof J?i.errorClass:"other"});}for(let i of kd(t))try{let o=Xt(i);s.push({manifest:o,rootDir:i,source:"npm"});}catch(o){a.component("#pack-loader").warn("npm pack manifest invalid",{errorClass:o instanceof J?o.errorClass:"other"});}let r=$.join(t,sa);if(I.existsSync(r)&&I.statSync(r).isDirectory()){let i=$.join(r,o$5),o;if(I.existsSync(i))try{o=Xt(r),s.push({manifest:o,rootDir:r,source:"local"});}catch(c){a.component("#pack-loader").warn("local pack manifest invalid",{errorClass:c instanceof J?c.errorClass:"other"});}let a$1=o?.id??"project";for(let c of _d(r))try{let l=Xt(c);s.push({manifest:l,rootDir:c,source:"local",parentPackId:a$1});}catch(l){a.component("#pack-loader").warn("discipline sub-pack manifest invalid",{errorClass:l instanceof J?l.errorClass:"other"});}}return xd(t,s),s}function kd(t){let e=$.join(t,"package.json");if(!I.existsSync(e))return [];let s;try{s=JSON.parse(I.readFileSync(e,"utf8"));}catch{return []}let n=new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{}),...Object.keys(s.peerDependencies||{})]);if(n.size===0)return [];let r=$.join(t,"node_modules");if(!I.existsSync(r))return [];let i=[];for(let o of n){if(o===ra)continue;let a=$.join(r,o,"package.json");if(!I.existsSync(a))continue;let c;try{c=JSON.parse(I.readFileSync(a,"utf8"));}catch{continue}let l=c.paradigm?.universityPack;if(typeof l!="string"||l.length===0)continue;let d=$.resolve($.dirname(a),l);I.existsSync($.join(d,o$5))&&i.push(d);}return i}function _d(t){let e=[],s;try{s=I.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let n of s){if(!n.isDirectory()||n.name.startsWith("."))continue;let r=$.join(t,n.name);I.existsSync($.join(r,o$5))&&e.push(r);}return e}function Qt(t,e){if(typeof t!="string"||t.length===0)throw new Error("resolveEntryAddress: address must be a non-empty string");let s=t.indexOf(":");if(s!==-1){let r=t.slice(0,s),i=t.slice(s+1);if(!r||!i)throw new Error("resolveEntryAddress: malformed <pack-id>:<entry-id> address");return {packId:r,entryId:i}}let n=t;if(e.candidatePacks&&e.entryExistsIn){let r=e.candidatePacks.filter(i=>e.entryExistsIn(i,n));if(r.length>1){let i=r.map(o=>`${o}:${n}`).join(", ");throw new Error(`resolveEntryAddress: bare entry id "${n}" is ambiguous across packs. Candidates: ${i}`)}if(r.length===1)return {packId:r[0],entryId:n}}return {packId:e.activePack,entryId:n}}function oa(t){try{return I.statSync($.join(t,"node_modules")).mtime.getTime()}catch{return}}function aa(t){try{return I.statSync($.join(t,sa)).mtime.getTime()}catch{return}}function Sd(t){let e=$.join(t,ia);if(!I.existsSync(e))return null;let s;try{s=JSON.parse(I.readFileSync(e,"utf8"));}catch{return null}if(s.version!==1||!Array.isArray(s.packs))return null;let n=oa(t),r=aa(t);return s.node_modules_mtime_ms!==n||s.local_university_mtime_ms!==r?null:s.packs.map(i=>({manifest:i.manifest,rootDir:i.rootDir,source:i.source,...i.parentPackId?{parentPackId:i.parentPackId}:{}}))}function xd(t,e){let s=$.join(t,ia);try{I.mkdirSync($.dirname(s),{recursive:!0});let n={version:1,node_modules_mtime_ms:oa(t),local_university_mtime_ms:aa(t),packs:e.map(r=>({manifest:r.manifest,rootDir:r.rootDir,source:r.source,...r.parentPackId?{parentPackId:r.parentPackId}:{}}))};I.writeFileSync(s,JSON.stringify(n,null,2),"utf8");}catch{}}function ca(){let t=process.env.PARADIGM_AUTHOR;if(t)return gr(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return gr(e)}catch{}try{let e=Ni.userInfo().username;if(e)return gr(e)}catch{}return "unknown"}function gr(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function la(){return new Date().toISOString().slice(0,10)}function Be(t,e){let s=[];try{s=ur(t);}catch{}if(e){let c=s.find(l=>l.manifest.id===e);if(c)return {packId:c.manifest.id,packRoot:c.rootDir,packs:s}}let n=s.find(c=>c.manifest.tenant_kind==="project");if(n)return {packId:n.manifest.id,packRoot:n.rootDir,packs:s};let r=s.find(c=>c.manifest.tenant_kind==="first-party");if(r)return {packId:r.manifest.id,packRoot:r.rootDir,packs:s};let i=q$3(t);return {packId:r$2(i)?.id??"project",packRoot:i,packs:s}}var Rd=$.join(".paradigm","university");function Ve(t,e){return $.resolve(e)===$.resolve(t,Rd)}function pa(){return [{name:"paradigm_university_search",description:"Search university content by type, tag, difficulty, or symbol. v6.0: result ids are <pack-id>:<entry-id> (minor-breaking). ~150 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Filter by content type"},tag:{type:"string",description:"Filter by tag prefix"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Filter by difficulty level"},symbol:{type:"string",description:'Filter by Paradigm symbol (e.g., "#api-gateway")'},query:{type:"string",description:"Free-text search in title and tags"},category:{type:"string",description:'Filter by category ID (e.g., "paradigm-core", "extracurricular")'},track:{type:"string",enum:["core","extracurricular"],description:"Filter by track"},pack:{type:"string",description:"v6.0: target a specific content pack by id (default: project pack if present, else first-party)"},section:{type:"string",description:"v6.5: filter by section id (within the active pack)"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_get",description:"Fetch a content item by ID. Accepts bare id or <pack-id>:<entry-id>. Returns full content (body for notes/policies, questions for quizzes). ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID: bare (N-foo) or qualified (paradigm:N-foo)"},pack:{type:"string",description:"v6.0: disambiguate a bare id against a specific pack (optional)"}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_create",description:"Create a new university content item (note, policy, quiz, or path). v6.0: honors optional pack selector. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["note","policy","guide","runbook","quiz","path"],description:"Content type to create"},title:{type:"string",description:"Content title"},body:{type:"string",description:"Markdown body for notes/policies. Quiz/path YAML content for those types."},tags:{type:"array",items:{type:"string"},description:"Tags for classification"},symbols:{type:"array",items:{type:"string"},description:"Paradigm symbols referenced by this content"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"],description:"Difficulty level (default: beginner)"},estimatedMinutes:{type:"number",description:"Estimated reading/completion time in minutes"},prerequisites:{type:"array",items:{type:"string"},description:"IDs of prerequisite content items"},category:{type:"string",description:"Category ID for the content (default: project defaultCategory)"},pack:{type:"string",description:"v6.0: target a specific pack by id (default: project pack)"},passThreshold:{type:"number",description:"For quizzes: pass threshold 0.0-1.0 (default: 0.7)"},questions:{type:"array",description:"For quizzes: array of {id, question, choices: {A:..., B:...}, correct, explanation?}"},ordered:{type:"boolean",description:"For learning paths: whether steps must be completed in order"},steps:{type:"array",description:"For learning paths: array of {content, required, passRequired?, note?}"}},required:["type","title"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_update",description:"Update an existing content item. id accepts bare or <pack-id>:<entry-id>. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to update (bare or qualified)"},pack:{type:"string",description:"v6.0: disambiguate a bare id against a specific pack (optional)"},title:{type:"string",description:"New title"},body:{type:"string",description:"New body content"},tags:{type:"array",items:{type:"string"},description:"New tags"},symbols:{type:"array",items:{type:"string"},description:"New symbols"},difficulty:{type:"string",enum:["beginner","intermediate","advanced"]},estimatedMinutes:{type:"number"},category:{type:"string",description:"Category ID for the content"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_university_onboard",description:"Get recommended onboarding sequence. v6.0: honors optional pack selector. ~200 tokens.",inputSchema:{type:"object",properties:{student:{type:"string",description:"Student name to check completion (auto-resolved if omitted)"},pack:{type:"string",description:"v6.0: target a specific pack (default: project pack)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_validate",description:"Validate content integrity. v6.0: honors optional pack selector. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Content ID to validate (bare or qualified; validates all if omitted)"},pack:{type:"string",description:"v6.0: target a specific pack (default: all packs)"},deep:{type:"boolean",description:"Enable deep cross-reference checks against scan-index (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_university_pack_list",description:"v6.0: List discovered content packs with manifest metadata. ~200 tokens.",inputSchema:{type:"object",properties:{tenant_kind:{type:"string",enum:["first-party","project","external"],description:"Filter by tenant kind"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ua(t,e,s){if(t==="paradigm_university_pack_list"){let n=e.tenant_kind,r=[];try{r=ur(s.rootDir);}catch{r=[];}let o={packs:(n?r.filter(c=>c.manifest.tenant_kind===n):r).map(c=>{let l=(c.manifest.sections??[]).slice().sort((d,u)=>d.order-u.order||d.id.localeCompare(u.id));return {id:c.manifest.id,name:c.manifest.name,version:c.manifest.version,tenant_kind:c.manifest.tenant_kind,...c.manifest.disciplines&&c.manifest.disciplines.length>0?{discipline:c.manifest.disciplines[0]}:{},entry_count:A$2(c.rootDir),sections:l,path:c.rootDir}})},a=JSON.stringify(o,null,2);return O(a.length,t),{handled:true,text:a}}if(t==="paradigm_university_search"){let n=e.pack,{packId:r,packRoot:i}=Be(s.rootDir,n),a=r$2(i)?.sections?.find(p=>p.default===true)?.id??"main",{entries:c,total:l,returned:d}=z$4(s.rootDir,{type:e.type,tag:e.tag,difficulty:e.difficulty,symbol:e.symbol,query:e.query,category:e.category,track:e.track,section:e.section,limit:e.limit},n?i:void 0),u=JSON.stringify({count:c.length,total:l,returned:d,truncated:l>d,pack:r,results:c.map(p=>({id:`${r}:${p.id}`,title:p.title,type:p.type,difficulty:p.difficulty,tags:p.tags,symbols:p.symbols,section:p.section??a,...typeof p.order=="number"?{order:p.order}:{}}))},null,2);return O(u.length,t),{handled:true,text:u}}if(t==="paradigm_university_get"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let r=e.pack,{packId:i,packRoot:o}=Be(s.rootDir,r),a;try{a=Qt(n,{activePack:i}).entryId;}catch{a=n;}let c=t$2(s.rootDir,a,o);if(c){let p=JSON.stringify({id:c.frontmatter.id,title:c.frontmatter.title,type:c.frontmatter.type,author:c.frontmatter.author,created:c.frontmatter.created,updated:c.frontmatter.updated,tags:c.frontmatter.tags,symbols:c.frontmatter.symbols,difficulty:c.frontmatter.difficulty,prerequisites:c.frontmatter.prerequisites,body:c.body},null,2);return O(p.length,t),{handled:true,text:p}}let l=v$3(s.rootDir,a,o);if(l){let p=JSON.stringify(l,null,2);return O(p.length,t),{handled:true,text:p}}let d=x$1(s.rootDir,a,o);if(d){let p=JSON.stringify(d,null,2);return O(p.length,t),{handled:true,text:p}}let u=JSON.stringify({error:`Content "${n}" not found`});return O(u.length,t),{handled:true,text:u}}if(t==="paradigm_university_create"){let n=e.type,r=e.title;if(!n||!r)return {handled:true,text:JSON.stringify({error:"type and title are required"})};let i=e.pack,{packRoot:o}=Be(s.rootDir,i),a=ca(),c=la(),l=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40);if(n==="quiz"){let y=`Q-${l}`,f={id:y,title:r,description:e.body||"",author:a,created:c,updated:c,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,passThreshold:e.passThreshold??.7,questions:e.questions||[],...e.category?{category:e.category}:{}};w(s.rootDir,f,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let v=JSON.stringify({created:y,type:"quiz",file:`content/quizzes/${y}.yaml`},null,2);return O(v.length,t),{handled:true,text:v}}if(n==="path"){let y=`LP-${l}`,f={id:y,title:r,description:e.body||"",author:a,created:c,updated:c,tags:e.tags||[],ordered:e.ordered??true,steps:e.steps||[],...e.category?{category:e.category}:{}};y$1(s.rootDir,f,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let v=JSON.stringify({created:y,type:"path",file:`content/paths/${y}.yaml`},null,2);return O(v.length,t),{handled:true,text:v}}let u=`${n==="policy"?"P":"N"}-${l}`,p={id:u,title:r,type:n,author:a,created:c,updated:c,tags:e.tags||[],symbols:e.symbols||[],difficulty:e.difficulty||"beginner",estimatedMinutes:e.estimatedMinutes,prerequisites:e.prerequisites||[],...e.category?{category:e.category}:{}};u$1(s.rootDir,p,e.body||"",o),Ve(s.rootDir,o)&&B$2(s.rootDir);let m=JSON.stringify({created:u,type:n,file:`content/${n==="policy"?"policies":"notes"}/${u}.md`},null,2);return O(m.length,t),{handled:true,text:m}}if(t==="paradigm_university_update"){let n=e.id;if(!n)return {handled:true,text:JSON.stringify({error:"id is required"})};let r=e.pack,{packId:i,packRoot:o}=Be(s.rootDir,r),a;try{a=Qt(n,{activePack:i}).entryId;}catch{a=n;}let c=la(),l=t$2(s.rootDir,a,o);if(l){let g={...l.frontmatter};e.title&&(g.title=e.title),e.tags&&(g.tags=e.tags),e.symbols&&(g.symbols=e.symbols),e.difficulty&&(g.difficulty=e.difficulty),e.estimatedMinutes!==void 0&&(g.estimatedMinutes=e.estimatedMinutes),e.category!==void 0&&(g.category=e.category),g.updated=c;let m=e.body??l.body;u$1(s.rootDir,g,m,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let y=JSON.stringify({updated:a,type:g.type},null,2);return O(y.length,t),{handled:true,text:y}}let d=v$3(s.rootDir,a,o);if(d){e.title&&(d.title=e.title),e.tags&&(d.tags=e.tags),e.symbols&&(d.symbols=e.symbols),e.difficulty&&(d.difficulty=e.difficulty),e.category!==void 0&&(d.category=e.category),d.updated=c,w(s.rootDir,d,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let g=JSON.stringify({updated:a,type:"quiz"},null,2);return O(g.length,t),{handled:true,text:g}}let u=x$1(s.rootDir,a,o);if(u){e.title&&(u.title=e.title),e.tags&&(u.tags=e.tags),e.category!==void 0&&(u.category=e.category),u.updated=c,y$1(s.rootDir,u,o),Ve(s.rootDir,o)&&B$2(s.rootDir);let g=JSON.stringify({updated:a,type:"path"},null,2);return O(g.length,t),{handled:true,text:g}}let p=JSON.stringify({error:`Content "${n}" not found`});return O(p.length,t),{handled:true,text:p}}if(t==="paradigm_university_onboard"){let n=e.student||ca(),r=e.pack,{packId:i,packRoot:o}=Be(s.rootDir,r),a=s$3(s.rootDir).branding.name;if(r){let d=r$2(o);d?.name&&(a=d.name);}let c=E$1(s.rootDir,n,r?o:void 0),l=JSON.stringify({university:a,pack:i,student:n,...c},null,2);return O(l.length,t),{handled:true,text:l}}if(t==="paradigm_university_validate"){let n=e.pack,{packId:r,packRoot:i}=Be(s.rootDir,n),o=e.id,a=o;if(o)try{a=Qt(o,{activePack:r}).entryId;}catch{}let c=C$2(s.rootDir,{id:a,deep:e.deep},n?i:void 0),l=JSON.stringify({pack:r,...c},null,2);return O(l.length,t),{handled:true,text:l}}return {handled:false,text:""}}function Td(t){try{let e=$.join(t,".paradigm","config.yaml");if(I.existsSync(e)){let n=qe.load(I.readFileSync(e,"utf-8")).platform;if(n?.port&&typeof n.port=="number")return n.port}}catch{}return 3850}function Pd(t){try{let e=$.join(t,".paradigm","config.yaml");if(I.existsSync(e)){let s=qe.load(I.readFileSync(e,"utf-8")),n=s.project||$.basename(t),r=s.role||"core";return `${n}/${r}`}}catch{}return `${$.basename(t)}/core`}async function Xe(t,e,s){let n=Td(t),r=Pd(t),i=`http://localhost:${n}/api/platform/agent-command`;try{let o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,agentId:r,payload:s}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let c=await o.text();return {ok:!1,error:`HTTP ${o.status}: ${c}`}}return {ok:!0,data:await o.json()}}catch(o){return {ok:false,error:`Platform server unreachable (${o instanceof Error?o.message:String(o)}). Is \`paradigm serve\` running?`}}}function ga(){return [{name:"paradigm_platform_navigate",description:"Navigate the Platform UI to a section, select a symbol, or open a lore entry. The browser updates in real-time. If the user is actively interacting, shows a prompt instead of auto-navigating. ~100 tokens.",inputSchema:{type:"object",properties:{section:{type:"string",enum:["overview","lore","graph","sentinel","university","symphony"],description:"Section to navigate to"},symbol:{type:"string",description:'Symbol to select (e.g., "#payment-service")'},loreId:{type:"string",description:"Lore entry ID to open in lore section"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_highlight",description:"Temporarily highlight symbols in the Platform UI with a pulsing glow. Auto-expires after duration. Use to draw attention to specific components during explanations. ~100 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbol IDs to highlight (e.g., ["#payment-service", "#api-gateway"])'},color:{type:"string",description:"Highlight color (CSS color, defaults to agent color)"},duration:{type:"number",description:"Duration in milliseconds (default: 5000)"},pulse:{type:"boolean",description:"Whether to pulse the highlight (default: true)"},label:{type:"string",description:"Optional label shown near highlighted symbols"}},required:["symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_annotate",description:"Show a toast notification, callout on a graph node, or badge in the Platform UI. Use for communicating decisions, warnings, or context to the user visually. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["toast","callout","badge"],description:"Annotation type: toast (notification), callout (floating note on graph node), badge (icon on symbol)"},message:{type:"string",description:"Annotation message text"},symbol:{type:"string",description:"Symbol to attach callout/badge to (required for callout/badge)"},severity:{type:"string",enum:["info","warning","error","success"],description:"Visual severity (default: info)"},duration:{type:"number",description:"Auto-dismiss duration in milliseconds (default: 6000, 0 = persistent)"}},required:["type","message"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_platform_observe",description:"Read the current Platform UI state: what section the user is viewing, what symbol is selected, theme, connected agents, and active highlights/annotations. ~150 tokens.",inputSchema:{type:"object",properties:{detail:{type:"string",enum:["summary","full"],description:"Level of detail (default: summary)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_platform_clear",description:"Remove agent highlights, annotations, or all agent effects from the Platform UI. ~50 tokens.",inputSchema:{type:"object",properties:{target:{type:"string",enum:["highlights","annotations","all"],description:"What to clear (default: all)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function fa(t,e,s){switch(t){case "paradigm_platform_navigate":{let n=await Xe(s.projectDir,"navigate",{section:e.section,symbol:e.symbol,loreId:e.loreId});if(!n.ok)return {handled:true,text:`**Navigate failed:** ${n.error}`};let r=n.data;if(r.navigated){let i=[];r.section&&i.push(`section: **${r.section}**`),r.symbol&&i.push(`symbol: **${r.symbol}**`);let o=r.userActive?" (user was active \u2014 shown as prompt)":"";return {handled:true,text:`Navigated to ${i.join(", ")}${o}`}}return {handled:true,text:`Navigation skipped: ${r.reason}`}}case "paradigm_platform_highlight":{let n=await Xe(s.projectDir,"highlight",{symbols:e.symbols,color:e.color,duration:e.duration,pulse:e.pulse,label:e.label});if(!n.ok)return {handled:true,text:`**Highlight failed:** ${n.error}`};let r=n.data;return r.highlighted?{handled:true,text:`Highlighted **${r.count}** symbol(s)${e.label?` with label "${e.label}"`:""}`}:{handled:true,text:`Highlight skipped: ${r.reason}`}}case "paradigm_platform_annotate":{let n=await Xe(s.projectDir,"annotate",{type:e.type,message:e.message,symbol:e.symbol,severity:e.severity,duration:e.duration});if(!n.ok)return {handled:true,text:`**Annotate failed:** ${n.error}`};let r=n.data;return r.annotated?{handled:true,text:`Created ${e.type} annotation: "${e.message}"`}:{handled:true,text:`Annotation skipped: ${r.reason}`}}case "paradigm_platform_observe":{let n=await Xe(s.projectDir,"observe",{detail:e.detail});if(!n.ok)return {handled:true,text:`**Observe failed:** ${n.error}`};let r=n.data,i=r.state,o=[`## Platform UI State
127
127
  `];o.push(`- **Connected:** ${r.connected?"Yes":"No"} (${r.users} browser client(s))`),o.push(`- **Section:** ${i.section}`),o.push(`- **Selected symbol:** ${i.selectedSymbol||"none"}`),o.push(`- **Theme:** ${i.theme}`),o.push(`- **Muted:** ${i.muted?"Yes \u2014 agent actions silently discarded":"No"}`);let a=r.agents;if(a?.length){o.push(`
128
128
  ### Connected Agents (${a.length})`);for(let c of a)o.push(`- \`${c.agentId}\` (since ${c.connectedAt})`);}if(e.detail==="full"){let c=r.highlights,l=r.annotations;c?.length&&o.push(`
129
129
  ### Active Highlights: ${c.length}`),l?.length&&o.push(`
130
130
  ### Active Annotations: ${l.length}`);}return {handled:true,text:o.join(`
131
- `)}}case "paradigm_platform_clear":{let n=await Xe(s.projectDir,"clear",{target:e.target});return n.ok?{handled:true,text:`Cleared ${n.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${n.error}`}}default:return {handled:false,text:""}}}z$2();function ma(){return [{name:"paradigm_agent_list",description:"List all agent identity profiles with top expertise areas. Shows agents from both global (~/.paradigm/agents/) and project (.paradigm/agents/) scopes. Returns profile summaries with personality and top symbols. ~150 tokens.",inputSchema:{type:"object",properties:{scope:{type:"string",enum:["all","global","project"],description:"Filter by scope (default: all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_expertise",description:"Find which agents are best qualified to work on a specific symbol. Returns agents ranked by confidence score from their expertise history. Use for symbol-to-agent routing. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to query (e.g., "#auth-middleware", "$checkout-flow")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns only top agent (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_get",description:"Get full agent profile including personality, expertise table, transferable patterns, and per-project contexts. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID or nickname (e.g., "architect", "Apex", "Jinx")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_bench",description:"Bench an agent \u2014 Maestro will skip this agent during orchestration and nomination scoring. Use when an agent is noisy or unhelpful. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to bench (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_agent_activate",description:"Activate a benched agent \u2014 restore it to active Maestro orchestration. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to activate (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ya(t,e,s){switch(t){case "paradigm_agent_list":{let n=i$2(s.rootDir),r=b$9(s.rootDir);if(n.length===0)return {handled:true,text:JSON.stringify({count:0,agents:[],note:"No .agent profiles found. Create one with `paradigm agent create <id> --global` or via paradigm_agent_create."},null,2)};let i=r?n.filter(l=>r.includes(l.id)):n,o=r?n.length-i.length:0,a=i$3(s.rootDir),c=new Map(a.map(l=>[l.id,l]));return {handled:true,text:JSON.stringify({count:i.length,totalAvailable:n.length,...r?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:i.map(l=>{let d=c.get(l.id);return {id:l.id,role:l.role,nickname:l.nickname,personality:l.personality,...d?{lastSession:d.lastSession?.summary?.slice(0,100),lastSessionAge:d.lastSession?.date,pendingWork:d.pendingWork?.length||0,sessionsOnProject:d.sessionsOnProject||0}:{},topExpertise:(l.expertise||[]).sort((u,p)=>p.confidence-u.confidence).slice(0,5).map(u=>({symbol:u.symbol,confidence:parseFloat(u.confidence.toFixed(2)),sessions:u.sessions})),projectContexts:Object.keys(l.contexts||{}),transferableCount:(l.transferable||[]).length,...l.attention?.threshold!=null?{threshold:l.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let n=e.symbol,r=e.response_format,i=l$4(s.rootDir,n);return r==="concise"?{handled:true,text:JSON.stringify({symbol:n,topAgent:i.length>0?{id:i[0].agentId,confidence:parseFloat(i[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:n,agents:i.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:i.length,...i.length===0?{note:`No agents have recorded expertise on ${n}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let n=e.id,r=h$4(s.rootDir,n);if(!r){let o=i$2(s.rootDir),a=n.toLowerCase(),c=o.filter(l=>l.nickname?.toLowerCase().includes(a)||l.id.includes(a));return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found by ID or nickname`,...c.length>0?{didYouMean:c.map(l=>({id:l.id,nickname:l.nickname}))}:{suggestion:`Create with \`paradigm agent create ${n} --global\``}},null,2)}}let i=y$2(r);return {handled:true,text:JSON.stringify({id:r.id,role:r.role,description:r.description,version:r.version,personality:r.personality,expertise:(r.expertise||[]).sort((o,a)=>a.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(r.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:r.contexts,created:r.created,updated:r.updated,...r.permissions?{permissions:r.permissions}:{},integrity:i},null,2)}}case "paradigm_agent_bench":{let n=e.id,r=h$4(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let i=r.id,o=b$9(s.rootDir);return o?o=o.filter(a=>a!==i):o=e$6().filter(a=>a!==i),d$6(s.rootDir,o),{handled:true,text:JSON.stringify({id:i,...r.nickname?{nickname:r.nickname}:{},removedFromRoster:true,rosterCount:o.length,note:`${r.nickname||i} (${i}) removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let n=e.id,r=h$4(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let i=r.id,o=b$9(s.rootDir);return o&&(o.includes(i)||(o.push(i),d$6(s.rootDir,o))),{handled:true,text:JSON.stringify({id:i,...r.nickname?{nickname:r.nickname}:{},addedToRoster:true,rosterCount:o?.length??"all (no roster)",note:`${r.nickname||i} (${i}) is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}var va=$.join(".paradigm","authority.yaml");async function ha(t){let e=$.join(t,va),s;try{s=await Qe.readFile(e,"utf8");}catch(r){if(r.code==="ENOENT")return null;throw r}let n=qe.load(s);return n==null||typeof n!="object"?{version:"1.0",schema:"v0-experimental",claims:{}}:((!n.claims||typeof n.claims!="object")&&(n.claims={}),n)}async function ba(t,e){let s=$.join(t,va);await Qe.mkdir($.dirname(s),{recursive:true});let n=qe.dump(e,{lineWidth:100,sortKeys:false});await Qe.writeFile(s,n,"utf8");}function wa(){return [{name:"paradigm_authority_claim",description:"Claim authority over a scope in .paradigm/authority.yaml. Idempotent on `scope` \u2014 re-claiming overwrites severity/claimant. Single-claimant-per-scope at v6.1. Severity vocab: advise|warn|block (policy stance, distinct from remediation severity). ~100 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:'Archetype id (e.g., "compliance")'},scope:{type:"string",description:'Scope key (e.g., "aspect-coverage", "aspect-drift", "anchor-staleness")'},severity:{type:"string",enum:["advise","warn","block"],description:"Policy stance. Default: advise."}},required:["claimant","scope"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_authority_release",description:"Release authority over a scope. Removes the claim entry from .paradigm/authority.yaml. Succeeds on archetype-default-created scopes (user/agent can override defaults). ~80 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:"Archetype id (used for audit; release is by scope key)"},scope:{type:"string",description:"Scope key to release"}},required:["claimant","scope"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function ka(t,e,s){if(t==="paradigm_authority_claim"){let n=e.claimant,r=e.scope,i=e.severity??"advise";if(!n||!r)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let o=new Date().toISOString(),a={claimant:n,severity:i,since:o,source:"explicit"},c=await ha(s.rootDir)??{version:"1.0",schema:"v0-experimental",claims:{}};return c.claims[r]=a,await ba(s.rootDir,c),{handled:true,text:JSON.stringify({scope:r,claimant:n,severity:i,source:"explicit",since:o},null,2)}}if(t==="paradigm_authority_release"){let n=e.claimant,r=e.scope;if(!n||!r)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let i=await ha(s.rootDir);if(!i||!(r in i.claims))return {handled:true,text:JSON.stringify({scope:r,released:false,note:"no active claim on this scope"},null,2)};let o=i.claims[r].claimant;return delete i.claims[r],await ba(s.rootDir,i),{handled:true,text:JSON.stringify({scope:r,released:true,previousClaimant:o},null,2)}}return {handled:false,text:""}}i();function _a(){return [{name:"paradigm_notebook_search",description:"Search agent notebook entries by concept, tag, or keyword. Notebooks are curated snippet libraries distilled from lore for reuse in orchestration. ~150 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:'Agent ID to search notebooks for (e.g., "architect", "builder")'},query:{type:"string",description:"Search query \u2014 matches concepts, tags, context, and snippet content"},concepts:{type:"array",items:{type:"string"},description:'Filter by concept tags (e.g., ["auth", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Filter by classification tags"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level (default: "detailed")'}},required:["agentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_notebook_add",description:"Add a new entry to an agent's notebook. Use for curated, reusable snippets that should be available across sessions. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add notebook entry for"},context:{type:"string",description:"When to apply this snippet \u2014 the retrieval context"},snippet:{type:"string",description:"The reusable code/knowledge snippet"},concepts:{type:"array",items:{type:"string"},description:'Concept tags for retrieval (e.g., ["auth", "jwt", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Classification tags"},confidence:{type:"number",description:"Confidence score 0.0-1.0 (default: 0.7)"},scope:{type:"string",enum:["global","project"],description:'Where to store: global travels across projects (default: "global")'},parentId:{type:"string",description:"Optional: ID of the parent notebook entry this was derived from (soft provenance, no validation)"},lineageType:{type:"string",enum:["fix","derive","capture","promote"],description:"Optional: relationship to parent \u2014 fix (corrects parent), derive (modified from parent), capture (new observation), promote (promoted from lower confidence)"}},required:["agentId","context","snippet","concepts"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_notebook_promote",description:"Extract a lore entry into a notebook entry. Distills the lore into a reusable snippet with provenance linking. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add the promoted entry to"},loreEntryId:{type:"string",description:'Lore entry ID to promote (e.g., "L-2026-03-15-...")'},scope:{type:"string",enum:["global","project"],description:'Where to store (default: "global")'}},required:["agentId","loreEntryId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Sa(t,e,s){switch(t){case "paradigm_notebook_search":{let n=e.agentId,r=e.query,i=e.concepts,o=e.tags,a=e.response_format,c;return r?c=c$5(n,r,s.rootDir):c=b$a(n,s.rootDir,{concepts:i,tags:o}),a==="concise"?{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,concepts:l.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,snippet:l.snippet.length>500?l.snippet.slice(0,500)+"...":l.snippet,concepts:l.concepts,tags:l.tags,appliedCount:l.appliedCount,confidence:l.confidence,provenance:l.provenance}))},null,2)}}case "paradigm_notebook_add":{let n=e.agentId,r=e.context,i=e.snippet,o=e.concepts||[],a=e.tags||[],c=e.confidence??.7,l=e.scope||(s.rootDir?"project":"global"),d=e.parentId,u=e.lineageType,p=e.publishable,g=e.scope,m={context:r,snippet:i,provenance:{source:"manual",createdBy:n},confidence:c,concepts:o,tags:a,...g?{scope:g}:{},...p!==void 0?{publishable:p}:{},...d?{parentId:d}:{},...u?{lineageType:u}:{}},y=e$7(n,m,l,s.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:y.entry.id,agentId:n,scope:l,filePath:y.filePath,concepts:y.entry.concepts,...d?{parentId:d}:{},...u?{lineageType:u}:{}},null,2)}}case "paradigm_notebook_promote":{let n=e.agentId,r=e.loreEntryId,i=e.scope||(s.rootDir?"project":"global"),o=await f$3(n,r,s.rootDir,i);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:n,loreEntryId:r,scope:i,publishScope:o.entry.scope,publishable:o.entry.publishable,filePath:o.filePath,concepts:o.entry.concepts,confidence:o.entry.confidence,note:o.entry.scope!=="generalizable"?`scope auto-classified as "${o.entry.scope}" \u2014 confirm or override with "nevr notebook audit"`:void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry "${r}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}var Td=".paradigm/scan-index.json",jd=".paradigm/flow-index.json",Od=".paradigm/config.yaml",Ad="portal.yaml",Id=".paradigm/university/index.yaml",X={enabled:true,title:null,theme:"dark",customCss:null,customContent:"docs/",exclude:{tags:[],patterns:[]},sidebar:{collapsed:[]},output:".paradigm/docs-site"};function tt(t){let e=$.join(t,Od);if(!A.existsSync(e))return {...X};try{let s=A.readFileSync(e,"utf8"),n=qe.load(s);if(!n||!n.docs)return {...X};let r=n.docs;return {enabled:r.enabled??X.enabled,title:r.title??X.title,theme:r.theme??X.theme,customCss:r.customCss??X.customCss,customContent:r.customContent??X.customContent,exclude:{tags:r.exclude?.tags??X.exclude.tags,patterns:r.exclude?.patterns??X.exclude.patterns},sidebar:{collapsed:r.sidebar?.collapsed??X.sidebar.collapsed},output:r.output??X.output}}catch{return {...X}}}function en(t){let e=$.join(t,Td);if(!A.existsSync(e))return null;try{let s=A.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function yr(t){let e=$.join(t,jd);if(!A.existsSync(e))return null;try{let s=A.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function tn(t){let e=$.join(t,Ad);if(!A.existsSync(e))return null;try{let s=A.readFileSync(e,"utf8");return qe.load(s)}catch{return null}}function Ca(t){let e=$.join(t,Id);if(!A.existsSync(e))return null;try{let s=A.readFileSync(e,"utf8");return qe.load(s)}catch{return null}}function Ra(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:qe.load(e[1]),body:e[2].trim()}}catch{return null}}function Pa(t){let e=new Map,s=[t.components,t.features,t.flows,t.state,t.gates,t.signals,t.aspects];for(let n of s)if(n)for(let[r,i]of Object.entries(n))e.set(r,i);return e}function Dd(t){return {components:"component",features:"component",flows:"flow",state:"component",gates:"gate",signals:"signal",aspects:"aspect"}[t]||"component"}function et(t,e){if(e.exclude.tags.length>0&&t.visualTags){for(let s of t.visualTags)if(e.exclude.tags.includes(s))return true}if(e.exclude.patterns.length>0&&t.path){for(let s of e.exclude.patterns)if(s.endsWith("*")){let n=s.slice(0,-1);if(t.path.includes(n))return true}else if(t.path.includes(s))return true}return false}function Ta(t,e){let s=$.join(t,e);if(!A.existsSync(s))return [];let n=[];try{let r=A.readdirSync(s).filter(i=>i.endsWith(".md"));for(let i of r)try{let o=A.readFileSync($.join(s,i),"utf8"),a=i.replace(/\.md$/,""),c=Ra(o);c?n.push({slug:a,title:c.frontmatter.title||a,body:c.body,order:typeof c.frontmatter.order=="number"?c.frontmatter.order:void 0,description:c.frontmatter.description||void 0}):n.push({slug:a,title:a,body:o.trim()});}catch{}}catch{}return n.sort((r,i)=>r.order!=null&&i.order!=null?r.order-i.order:r.order!=null?-1:i.order!=null?1:r.title.localeCompare(i.title)),n}function ja(t,e,s){let n=s||tt(t),r=$.join(t,n.customContent),i=$.join(r,`${e}.md`);if(!A.existsSync(i))return null;try{let o=A.readFileSync(i,"utf8"),a=Ra(o);return a?{slug:e,title:a.frontmatter.title||e,body:a.body,order:typeof a.frontmatter.order=="number"?a.frontmatter.order:void 0,description:a.frontmatter.description||void 0}:{slug:e,title:e,body:o.trim()}}catch{return null}}function Oa(t,e){let s=e||tt(t),n=en(t),r=yr(t),i=tn(t),o=Ta(t,s.customContent),a=Ca(t),c=n?.$meta?.project||$.basename(t),l=s.title||`${c} Docs`,d=[],u={},p=0;if(o.length>0&&d.push({id:"custom-pages",label:"Pages",collapsed:s.sidebar.collapsed.includes("custom-pages"),items:o.map(g=>({id:g.slug,label:g.title,kind:"custom",description:g.description}))}),a&&a.entries.length>0){let g=a.entries.filter(m=>(m.type==="note"||m.type==="policy")&&m.symbols.length>0);g.length>0&&d.push({id:"guides",label:"Guides",collapsed:s.sidebar.collapsed.includes("guides"),items:g.map(m=>({id:m.id,label:m.title,kind:"guide",description:void 0,badge:m.symbols.length>0?`${m.symbols.length} symbols`:void 0}))});}if(n){let g=Object.values(n.components||{}).filter(k=>!et(k,s));if(g.length>0){let k=new Map;for(let C of g){let j=C.componentType||"other";k.has(j)||k.set(j,[]),k.get(j).push(C);}let T=[...k.entries()].sort((C,j)=>j[1].length-C[1].length).map(([C,j])=>({id:`components-${C}`,label:`${C.charAt(0).toUpperCase()+C.slice(1)} (${j.length})`,collapsed:s.sidebar.collapsed.includes(`components-${C}`),items:j.sort((O,R)=>O.name.localeCompare(R.name)).map(O=>({id:O.id,label:O.name,kind:"component",description:O.description,badge:O.componentType}))}));d.push({id:"components",label:`Components (${g.length})`,collapsed:s.sidebar.collapsed.includes("components"),items:[],subgroups:T}),u.components=g.length,p+=g.length;}let m=Object.values(n.features||{}).filter(k=>!et(k,s));m.length>0&&(d.push({id:"features",label:`Features (${m.length})`,collapsed:s.sidebar.collapsed.includes("features"),items:m.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"component",description:k.description}))}),u.features=m.length,p+=m.length);let y=Object.values(n.flows||{}).filter(k=>!et(k,s)),f=new Set(y.map(k=>k.id)),v=[];if(r)for(let[k,_]of Object.entries(r.flows)){let T=k.replace(/^\$/,"");f.has(T)||v.push({id:T,label:_.name||T,kind:"flow",description:_.description});}let h=[...y.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"flow",description:k.description})),...v];h.length>0&&(d.push({id:"flows",label:`Flows (${h.length})`,collapsed:s.sidebar.collapsed.includes("flows"),items:h}),u.flows=h.length,p+=h.length);let b=Object.values(n.gates||{}).filter(k=>!et(k,s));b.length>0&&(d.push({id:"gates",label:`Gates (${b.length})`,collapsed:s.sidebar.collapsed.includes("gates"),items:b.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"gate",description:k.description}))}),u.gates=b.length,p+=b.length);let w=Object.values(n.signals||{}).filter(k=>!et(k,s));w.length>0&&(d.push({id:"signals",label:`Signals (${w.length})`,collapsed:s.sidebar.collapsed.includes("signals"),items:w.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"signal",description:k.description}))}),u.signals=w.length,p+=w.length);let x=Object.values(n.aspects||{}).filter(k=>!et(k,s));x.length>0&&(d.push({id:"aspects",label:`Aspects (${x.length})`,collapsed:s.sidebar.collapsed.includes("aspects"),items:x.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"aspect",description:k.description}))}),u.aspects=x.length,p+=x.length);}if(i){let g=Object.keys(i.routes||{}).length,m=Object.keys(i.gates||{}).length;d.push({id:"portal",label:"Portal",collapsed:s.sidebar.collapsed.includes("portal"),items:[{id:"portal-overview",label:"Authorization Overview",kind:"portal",description:`${m} gates, ${g} routes`,badge:`${g} routes`}]});}return {title:l,project:c,generatedAt:new Date().toISOString(),groups:d,totalSymbols:p,symbolCounts:u}}function Aa(t,e){let s=en(t);if(!s)return null;let n=Pa(s),r=n.get(e);if(!r)return null;let i=[];for(let[f,v]of n)f!==e&&v.related&&v.related.includes(r.symbol)&&i.push(v.symbol);let o=(r.related||[]).slice(),a=[],c=yr(t);if(c)for(let[f,v]of Object.entries(c.flows)){let h=(v.steps||[]).map(b=>b.symbol);(h.includes(r.symbol)||h.includes(`#${e}`))&&a.push({id:f.replace(/^\$/,""),name:v.name||f});}if(s.flows)for(let[f,v]of Object.entries(s.flows)){if(a.some(b=>b.id===f))continue;let h=(v.steps||[]).map(b=>b.symbol).filter(Boolean);(h.includes(r.symbol)||h.includes(`#${e}`))&&a.push({id:f,name:v.name});}let l=[],d=tn(t);if(d&&r.category==="gates"){let f=Object.keys(d.gates||{}).find(v=>v.replace(/^\^/,"")===e);f&&l.push({id:f.replace(/^\^/,""),description:d.gates[f].description});}else if(d){let f=new Set((r.related||[]).filter(v=>v.startsWith("^")));for(let[v,h]of Object.entries(d.routes||{}))for(let b of h){let w=b.replace(/^\^/,"");if(f.has(b)||f.has(`^${w}`)){let x=d.gates[b]||d.gates[`^${w}`]||d.gates[w];x&&!l.some(k=>k.id===w)&&l.push({id:w,description:x.description});}}}let u=[];if(s.aspects)for(let[f,v]of Object.entries(s.aspects))v.related&&v.related.includes(r.symbol)&&u.push(v.symbol);for(let f of r.related||[])f.startsWith("~")&&!u.includes(f)&&u.push(f);let p=[],g=Ca(t);if(g)for(let f of g.entries)f.symbols.includes(r.symbol)&&p.push({id:f.id,title:f.title});let m=r.parent||void 0,y=[];if(s.components)for(let f of Object.values(s.components))f.parent===r.symbol&&y.push(f.symbol);return {id:r.id,symbol:r.symbol,name:r.name,description:r.description||"",category:r.category||"components",componentType:r.componentType,tags:r.visualTags||[],path:r.path||"",related:r.related||[],referencedBy:i,references:o,flows:a,gates:l,aspects:u,guides:p,parent:m,children:y}}function Ia(t,e){let s=yr(t),n=en(t);if(s){let r=s.flows[`$${e}`]?`$${e}`:e,i=s.flows[r];if(i){let o=(i.steps||[]).map(c=>({type:c.type||"action",symbol:c.symbol||"",description:c.description})),a=n?.flows?.[e.replace(/^\$/,"")];return {id:e.replace(/^\$/,""),symbol:`$${e.replace(/^\$/,"")}`,name:i.name||e,description:i.description,trigger:i.trigger,steps:o,successSignal:i.successSignal,errorSignal:i.errorSignal,tags:a?.visualTags||[],path:a?.path||i.definedIn||""}}}if(n?.flows){let r=e.replace(/^\$/,""),i=n.flows[r];if(i){let o=(i.steps||[]).map(a=>({type:"action",symbol:a.symbol||"",description:a.action||a.name}));return {id:r,symbol:`$${r}`,name:i.name,description:i.description,steps:o,tags:i.visualTags||[],path:i.path||""}}}return null}function Da(t){let e=tn(t);if(!e)return {version:"0",gates:[],routes:[]};let s=new Map;for(let[i,o]of Object.entries(e.routes||{}))for(let a of o){let c=a.replace(/^\^/,"");s.has(c)||s.set(c,[]),s.get(c).push(i);}let n=Object.entries(e.gates||{}).map(([i,o])=>{let a=i.replace(/^\^/,"");return {symbol:`^${a}`,description:o.description,check:o.check,routes:s.get(a)||[]}}),r=Object.entries(e.routes||{}).map(([i,o])=>{let a=i.indexOf(" "),c=a>0?i.substring(0,a):"GET";return {route:a>0?i.substring(a+1):i,method:c,gates:o.map(d=>{let u=d.replace(/^\^/,""),p=e.gates[d]||e.gates[`^${u}`]||e.gates[u];return {symbol:`^${u}`,description:p?.description}})}});return {version:e.version||"1.0",gates:n,routes:r}}function $a(t,e,s){let n=s||20,r=[],i=e.toLowerCase(),o=en(t);if(o){let d=Pa(o);for(let[u,p]of d){let g=mr(p.name,p.description||"",p.visualTags||[],i);g>0&&r.push({id:p.id,kind:Dd(p.category),label:p.name,description:p.description||"",matchContext:xa(p.name,p.description||"",i),score:g});}}let a=tt(t),c=Ta(t,a.customContent);for(let d of c){let u=d.body.substring(0,200),p=mr(d.title,u,[],i);p>0&&r.push({id:d.slug,kind:"custom",label:d.title,description:d.description||u.substring(0,100),matchContext:xa(d.title,d.body,i),score:p});}let l=tn(t);if(l)for(let[d,u]of Object.entries(l.gates||{})){let p=d.replace(/^\^/,""),g=mr(p,u.description,[],i);g>0&&r.push({id:p,kind:"portal",label:`^${p}`,description:u.description,score:g});}return r.sort((d,u)=>u.score-d.score||d.label.localeCompare(u.label)),r.slice(0,n)}function mr(t,e,s,n){let r=t.toLowerCase(),i=e.toLowerCase();return r===n?1:r.startsWith(n)?.8:r.includes(n)?.6:i.includes(n)?.5:s.some(o=>o.toLowerCase().includes(n))?.3:0}function xa(t,e,s){let r=e.toLowerCase().indexOf(s);if(r<0)return t.toLowerCase().includes(s)?t:void 0;let i=Math.max(0,r-40),o=Math.min(e.length,r+s.length+40),a=e.substring(i,o).trim();return i>0&&(a=`...${a}`),o<e.length&&(a=`${a}...`),a}function Ha(){return [{name:"paradigm_docs_manifest",description:"Get the documentation sidebar manifest \u2014 all symbols grouped by type with counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_page",description:"Get page data for a symbol, flow, portal, or custom docs page. Returns structured data for rendering. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol ID (e.g., "cli-commands", "checkout-flow", "authenticated"). Do not include the prefix (#, $, ^, !, ~).'},flow:{type:"string",description:'Flow ID (e.g., "$init-flow"). Include the $ prefix.'},portal:{type:"boolean",description:"Set to true to get the portal overview page (gates + routes)."},slug:{type:"string",description:'Custom page slug (e.g., "getting-started").'}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_search",description:"Search across all documentation content \u2014 symbols, descriptions, tags, custom pages. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query string"},limit:{type:"number",description:"Maximum results (default: 20)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Fa(t,e,s){if(t==="paradigm_docs_manifest"){let n=tt(s.rootDir),r=Oa(s.rootDir,n),i=JSON.stringify(r,null,2);return O(i.length,t),{handled:true,text:i}}if(t==="paradigm_docs_page"){if(e.portal){let r=Da(s.rootDir),i=JSON.stringify(r,null,2);return O(i.length,t),{handled:true,text:i}}if(e.flow){let r=e.flow,i=Ia(s.rootDir,r);if(!i){let a=JSON.stringify({error:`Flow "${r}" not found`});return O(a.length,t),{handled:true,text:a}}let o=JSON.stringify(i,null,2);return O(o.length,t),{handled:true,text:o}}if(e.slug){let r=tt(s.rootDir),i=ja(s.rootDir,e.slug,r);if(!i){let a=JSON.stringify({error:`Page "${e.slug}" not found`});return O(a.length,t),{handled:true,text:a}}let o=JSON.stringify(i,null,2);return O(o.length,t),{handled:true,text:o}}if(e.symbol){let r=Aa(s.rootDir,e.symbol);if(!r){let o=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return O(o.length,t),{handled:true,text:o}}let i=JSON.stringify(r,null,2);return O(i.length,t),{handled:true,text:i}}let n=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return O(n.length,t),{handled:true,text:n}}if(t==="paradigm_docs_search"){let n=e.query;if(!n)return {handled:true,text:JSON.stringify({error:"query is required"})};let r=$a(s.rootDir,n,e.limit),i=JSON.stringify({count:r.length,results:r},null,2);return O(i.length,t),{handled:true,text:i}}return {handled:false,text:""}}g();e();function Na(){return [{name:"paradigm_work_log_record",description:"Record a work log entry \u2014 what got done. Auto-attached to sprint boards and standup summaries. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent that did the work (e.g., "builder")'},summary:{type:"string",description:"What was done"},outcome:{type:"string",enum:["pass","fail","partial","blocked"],description:"How it went"},task_ref:{type:"string",description:'Ticket/issue reference (e.g., "ENG-142")'},files_modified:{type:"array",items:{type:"string"},description:"Files that were modified"},symbols_touched:{type:"array",items:{type:"string"},description:"Paradigm symbols touched"},next_steps:{type:"array",items:{type:"string"},description:"What's left to do"},blockers:{type:"array",items:{type:"string"},description:"What's blocking progress"},duration_minutes:{type:"number",description:"How long it took"},commit:{type:"string",description:"Git commit hash"}},required:["agent","summary","outcome"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_work_log_search",description:"Search work log entries \u2014 what got done. Returns recent work, filterable by agent, outcome, symbol, date. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent"},outcome:{type:"string",enum:["pass","fail","partial","blocked"]},task_ref:{type:"string",description:"Filter by ticket reference"},symbol:{type:"string",description:"Filter by symbol touched"},dateFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},dateTo:{type:"string",description:"End date (YYYY-MM-DD)"},limit:{type:"number",description:"Max entries to return (default 20)"},summary:{type:"boolean",description:"Return aggregate summary instead of entries"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_journal_record",description:"Record a learning journal entry \u2014 what an agent learned. Agent-private, travels across projects. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent who learned this (e.g., "security")'},trigger:{type:"string",enum:["correction_received","confidence_miss","pattern_discovered","debate_loss","failure_analysis","human_feedback","self_reflection"],description:"What triggered this learning moment"},insight:{type:"string",description:"The insight itself"},project:{type:"string",description:"Project where this happened"},transferable:{type:"boolean",description:"Whether this applies to other projects"},confidence_before:{type:"number",description:"Confidence before (0.0-1.0)"},confidence_after:{type:"number",description:"Confidence after (0.0-1.0)"},pattern:{type:"object",properties:{id:{type:"string"},applies_when:{type:"string"},correct_approach:{type:"string"}}},linked_work_log:{type:"string",description:"Work log entry that prompted this"},tags:{type:"array",items:{type:"string"}}},required:["agent","trigger","insight","project","transferable"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_journal_search",description:"Search learning journal entries \u2014 what agents learned. Can search across all agents or a specific one. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent (omit for all agents)"},trigger:{type:"string",description:"Filter by trigger type"},project:{type:"string",description:"Filter by project"},transferable:{type:"boolean",description:"Only show transferable insights"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},stats:{type:"boolean",description:"Return stats instead of entries (requires agent)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_decision_record",description:"Record a team decision \u2014 what we decided and why. Institutional memory with rationale and alternatives. ~100 tokens.",inputSchema:{type:"object",properties:{title:{type:"string",description:"Decision title"},decision:{type:"string",description:"The decision itself"},rationale:{type:"string",description:"Why this was chosen"},participants:{type:"array",items:{type:"object",properties:{id:{type:"string"},role:{type:"string",enum:["human","agent"]},stance:{type:"string",enum:["proposed","supported","dissented","abstained","neutral"]}},required:["id","role","stance"]}},alternatives_considered:{type:"array",items:{type:"object",properties:{option:{type:"string"},rejected_because:{type:"string"}}}},symbols_affected:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","proposed"],description:"Decision status (default: active)"},tags:{type:"array",items:{type:"string"}}},required:["title","decision","rationale","participants"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_decision_search",description:"Search team decisions \u2014 what we decided. Find active decisions by symbol, participant, status. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["active","superseded","deprecated","proposed","rejected"]},participant:{type:"string",description:"Filter by participant ID"},symbol:{type:"string",description:"Filter by affected symbol"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},summary:{type:"boolean",description:"Return aggregate summary"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ea(t,e,s){let n=r=>JSON.stringify(r,null,2);switch(t){case "paradigm_work_log_record":{let r=c$2(s.rootDir),{filtered:i}=d(e.summary,r,"work_log"),o=a$a(s.rootDir,{agent:e.agent,summary:i,outcome:e.outcome,task_ref:e.task_ref,files_modified:e.files_modified,symbols_touched:e.symbols_touched,next_steps:e.next_steps,blockers:e.blockers,duration_minutes:e.duration_minutes,commit:e.commit});return {text:n({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let i=d$3(s.rootDir,7);return {text:n(i),handled:true}}let r=b$7(s.rootDir,{agent:e.agent,outcome:e.outcome,task_ref:e.task_ref,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:r.length,entries:r.map(i=>({id:i.id,agent:i.agent,summary:i.summary,outcome:i.outcome,timestamp:i.timestamp,symbols_touched:i.symbols_touched,task_ref:i.task_ref}))}),handled:true}}case "paradigm_journal_record":{let r=c$2(s.rootDir),{filtered:i}=d(e.insight,r,"learning_journal"),o=a$9(e.agent,{trigger:e.trigger,insight:i,project:e.project,transferable:e.transferable,confidence_before:e.confidence_before,confidence_after:e.confidence_after,pattern:e.pattern,linked_work_log:e.linked_work_log,tags:e.tags});return {text:n({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let i=e$3(e.agent);return {text:n(i),handled:true}}let r=e.agent?b$6(e.agent,{trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}):d$2({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:r.length,entries:r.map(i=>({id:i.id,agent:i.agent,trigger:i.trigger,insight:i.insight.slice(0,200),project:i.project,transferable:i.transferable,timestamp:i.timestamp}))}),handled:true}}case "paradigm_decision_record":{let r=c$2(s.rootDir),{filtered:i}=d(e.decision,r,"team_decisions"),{filtered:o}=d(e.rationale,r,"team_decisions"),a=a$8(s.rootDir,{title:e.title,decision:i,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags}),c=d$1(s.rootDir,a.id);return {text:n({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp,...c?{companion_lore_id:c}:{}}),handled:true}}case "paradigm_decision_search":{if(e.summary){let i=h$1(s.rootDir);return {text:n(i),handled:true}}let r=e$2(s.rootDir,{status:e.status,participant:e.participant,symbol:e.symbol,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:r.length,entries:r.map(i=>({id:i.id,title:i.title,status:i.status,decision:i.decision.slice(0,200),participants:i.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:i.symbols_affected,timestamp:i.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${t}`,handled:false}}}var kt=["purpose-coverage","purpose-exists","portal-gates","aspect-anchors","purpose-freshness","aspect-advisory","lore-required","habits-blocking","purpose-required-patterns","drift-detection","portal-compliance","graduation-tracking","orchestration-required"],qa={strict:{"purpose-coverage":"block","purpose-exists":"block","portal-gates":"block","aspect-anchors":"block","purpose-freshness":"warn","aspect-advisory":"warn","lore-required":"block","habits-blocking":"block","purpose-required-patterns":"block","drift-detection":"block","portal-compliance":"block","graduation-tracking":"warn","orchestration-required":"block"},balanced:{"purpose-coverage":"block","purpose-exists":"warn","portal-gates":"warn","aspect-anchors":"warn","purpose-freshness":"warn","aspect-advisory":"off","lore-required":"warn","habits-blocking":"block","purpose-required-patterns":"warn","drift-detection":"warn","portal-compliance":"warn","graduation-tracking":"off","orchestration-required":"warn"},minimal:{"purpose-coverage":"warn","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"warn","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"},none:{"purpose-coverage":"off","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"off","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"}};function nn(t){let e=$.join(t,".paradigm","config.yaml");if(!A.existsSync(e))return {};try{return qe.load(A.readFileSync(e,"utf8"))||{}}catch{return {}}}function hr(t,e){let s=$.join(t,".paradigm","config.yaml");A.writeFileSync(s,qe.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function rn(t){let e=t.enforcement?.level||"none",s=qa[e]||qa.none,n=t.enforcement?.checks||{},r=t.enforcement?.orchestration?.threshold??3,i={...s};for(let[o,a]of Object.entries(n))kt.includes(o)&&La(a)&&(i[o]=a);return i.orchestrationThreshold=r,i}function La(t){return t==="block"||t==="warn"||t==="off"}function $d(t){return t==="strict"||t==="balanced"||t==="minimal"||t==="none"}function Hd(t){return kt.includes(t)}var Fd=[{name:"paradigm_compliance_promote",description:"Record a user's response to Rune's enforcement-level promotion offer. Call this after presenting the symbol-tracking invitation. Response 'minimal' or 'balanced' enables enforcement at that level and records the promotion state; 'snooze' defers for 7 days; 'never' suppresses the offer permanently.",inputSchema:{type:"object",properties:{response:{type:"string",enum:["minimal","balanced","snooze","never"],description:"User's chosen response to the promotion offer"}},required:["response"]}},{name:"paradigm_enforcement_configure",description:"View or modify stop hook enforcement levels. Actions: status (view current), set-level (change preset), override (set per-check severity), reset (clear overrides). ~250 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["status","set-level","override","reset"],description:"Action to perform."},level:{type:"string",enum:["strict","balanced","minimal","none"],description:"Enforcement preset level (for set-level action)."},checkId:{type:"string",description:"Check ID to override (for override action). One of: "+kt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Nd(t,e){let{action:s,level:n,checkId:r,severity:i}=e;switch(s){case "status":{let o=nn(t.rootDir),a=rn(o),c=o.enforcement?.level||"none",l=o.enforcement?.checks||{},d=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:c,orchestrationThreshold:d,orchestrationNote:"Threshold is compared against magnitude score (not just file count). Magnitude = source files + cross-package penalty + security-adjacent penalty + symbol file changes.",overrides:Object.keys(l).length>0?l:void 0,effective:a,checkIds:[...kt],presetLevels:["strict","balanced","minimal","none"]},null,2)}case "set-level":{if(!n||!$d(n))return JSON.stringify({error:`Invalid level "${n}". Must be one of: strict, balanced, minimal, none`});let o=nn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=n,o.enforcement.checks={},hr(t.rootDir,o);let a=rn(o);return JSON.stringify({success:true,level:n,message:`Enforcement level set to "${n}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!r||!Hd(r))return JSON.stringify({error:`Invalid checkId "${r}". Must be one of: ${kt.join(", ")}`});if(!i||!La(i))return JSON.stringify({error:`Invalid severity "${i}". Must be one of: block, warn, off`});let o=nn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[r]=i,hr(t.rootDir,o);let a=rn(o);return JSON.stringify({success:true,checkId:r,severity:i,message:`Override set: ${r} = ${i}`,effective:a},null,2)}case "reset":{let o=nn(t.rootDir);o.enforcement&&(o.enforcement.checks={}),hr(t.rootDir,o);let a=rn(o),c=o.enforcement?.level||"none";return JSON.stringify({success:true,message:`All per-check overrides cleared. Preset "${c}" is now fully in effect.`,effective:a},null,2)}default:return JSON.stringify({error:`Unknown action "${s}". Must be one of: status, set-level, override, reset`})}}function Ma(){return Fd}async function Ga(t,e,s){if(t==="paradigm_enforcement_configure"){let n=await Nd(s,e);return O(n.length,"paradigm_enforcement_configure"),{handled:true,text:n}}if(t==="paradigm_compliance_promote"){let n=e.response,{recordPromotion:r}=await import('./rune-promotion-3JQ5LMWK.js');r(s.rootDir,n);let i;if(n==="minimal"||n==="balanced"){let o=$.join(s.rootDir,".paradigm","config.yaml");if(A.existsSync(o)){let a=qe.load(A.readFileSync(o,"utf8"));a&&typeof a=="object"&&((!a.enforcement||typeof a.enforcement!="object")&&(a.enforcement={}),a.enforcement.level=n,A.writeFileSync(o,qe.dump(a,{lineWidth:-1,noRefs:true,sortKeys:false}),"utf8"));}i=JSON.stringify({ok:true,message:`Symbol tracking enabled at "${n}". Rune is now active.`,level:n});}else n==="snooze"?i=JSON.stringify({ok:true,message:"Got it \u2014 I'll ask again in 7 days.",state:"snoozed"}):i=JSON.stringify({ok:true,message:"Understood. I won't bring this up again.",state:"never"});return O(i.length,"paradigm_compliance_promote"),{handled:true,text:i}}return {handled:false,text:""}}b$1();function Ja(){return [{name:"paradigm_arch_status",description:"Get the architectural layer map summary and drift report. Shows tiers, their components, and any symbols that are unassigned (not in any tier) or missing from the index. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_arch_diagram",description:"Render the architectural map as a Mermaid diagram. Returns a Mermaid graph TD string showing tiers and their links. ~150 tokens.",inputSchema:{type:"object",properties:{format:{type:"string",enum:["mermaid"],description:'Output format. Only "mermaid" supported (default: "mermaid").'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ua(t,e,s){try{if(t==="paradigm_arch_status"){let n=b$b(s.rootDir);if(!n)return {text:JSON.stringify({exists:!1,message:"No arch.yaml found. Create .paradigm/arch.yaml to start mapping your architecture."}),handled:!0};let r=d$7(s.rootDir,s);return {text:JSON.stringify({exists:!0,version:n.version,tierCount:n.tiers.length,tiers:n.tiers.map(i=>({id:i.id,label:i.label,responsibility:i.responsibility,framework:i.tech?.framework??"",componentCount:i.components.length,components:i.components})),links:n.links,drift:{unassigned:r.unassigned,missing_purpose:r.missing_purpose,clean:r.unassigned.length===0&&r.missing_purpose.length===0}}),handled:!0}}if(t==="paradigm_arch_diagram"){let n=b$b(s.rootDir);if(!n)return {text:JSON.stringify({error:"No arch.yaml found. Cannot render diagram."}),handled:!0};let r=e$8(n);return {text:JSON.stringify({format:"mermaid",diagram:r}),handled:!0}}return {handled:!1,text:""}}catch(n){return a.component("#arch-tools").warn(`Unexpected error in arch tool ${t}`,{error:String(n)}),{text:JSON.stringify({error:String(n)}),handled:true}}}function Ed(t,e){let s=[];for(let n=0;n<=e.length;n++)s[n]=[n];for(let n=0;n<=t.length;n++)s[0][n]=n;for(let n=1;n<=e.length;n++)for(let r=1;r<=t.length;r++)e.charAt(n-1)===t.charAt(r-1)?s[n][r]=s[n-1][r-1]:s[n][r]=Math.min(s[n-1][r-1]+1,s[n][r-1]+1,s[n-1][r]+1);return s[e.length][t.length]}function Wa(t,e,s={}){let{maxDistance:n=3,maxResults:r=5}=s,i=t.toLowerCase(),o=[];for(let a of e){let c=a.toLowerCase();if(c===i){o.push({match:a,distance:0});continue}if(c.includes(i)||i.includes(c)){o.push({match:a,distance:1});continue}let l=Ed(i,c);l<=n&&o.push({match:a,distance:l});}return o.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:a.match.localeCompare(c.match)),o.slice(0,r)}v();function Md(t$1,e){let s$1=new a$3(t$1),n=e||(async()=>{}),r$1=o=>async(a,c,l)=>o(a,c,l),i=o=>async(a,c,l)=>o(a,c,l,n);return s$1.registerAll([{key:"context",tier:"core",getToolsList:R,handleTool:r$1(S)},{key:"navigate",tier:"core",getToolsList:l$1,handleTool:r$1(m$1)},{key:"tags",tier:"core",getToolsList:Hi,handleTool:r$1(Fi)},{key:"purpose-portal",tier:"core",getToolsList:Ui,handleTool:i(Wi)},{key:"pm",tier:"core",getToolsList:ao,handleTool:r$1(co)},{key:"reindex",tier:"core",getToolsList:n$3,handleTool:i(o$1)},{key:"docs",tier:"core",getToolsList:Ha,handleTool:r$1(Fa)},{key:"ripple",tier:"core",getToolsList:q$1,handleTool:r$1(r)},{key:"captain",tier:"core",getToolsList:C,handleTool:r$1(D)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:s,handleTool:r$1(t)},{key:"history",tier:"feature",getToolsList:_i,handleTool:r$1(Si)},{key:"lore",tier:"feature",getToolsList:A$1,handleTool:r$1(B)},{key:"streams",tier:"feature",getToolsList:Na,handleTool:r$1(Ea)},{key:"ambient",tier:"feature",getToolsList:a$4,handleTool:r$1(b$3)},{key:"sentinel",tier:"feature",getToolsList:xi,handleTool:r$1(Ci)},{key:"flows",tier:"feature",getToolsList:Ri,handleTool:r$1(Pi)},{key:"fixtures",tier:"feature",getToolsList:Ii,handleTool:r$1(Di)},{key:"orchestration",tier:"feature",getToolsList:a$5,handleTool:r$1(b$4)},{key:"habits",tier:"feature",getToolsList:po,handleTool:r$1(uo)},{key:"tasks",tier:"feature",getToolsList:Co,handleTool:r$1(Ro)},{key:"personas",tier:"feature",getToolsList:Fo,handleTool:r$1(No)},{key:"protocols",tier:"feature",getToolsList:u,handleTool:r$1(v$1)},{key:"symphony",tier:"feature",getToolsList:Zo,handleTool:r$1(ea)},{key:"university",tier:"feature",getToolsList:pa,handleTool:r$1(ua)},{key:"agents",tier:"feature",getToolsList:ma,handleTool:r$1(ya)},{key:"authority",tier:"feature",getToolsList:wa,handleTool:r$1(ka)},{key:"propose-block",tier:"feature",getToolsList:a$6,handleTool:r$1(b$5)},{key:"notebooks",tier:"feature",getToolsList:_a,handleTool:r$1(Sa)},{key:"aspect-graph",tier:"feature",getToolsList:So,handleTool:r$1(xo)},{key:"enforcement",tier:"feature",getToolsList:Ma,handleTool:r$1(Ga),detect:o=>A.existsSync($.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Lo,handleTool:r$1(Mo),detect:o=>A.existsSync($.join(o,".paradigm","aspect-graph.db"))},{key:"arch",tier:"feature",getToolsList:Ja,handleTool:r$1(Ua),detect:o=>A.existsSync($.join(o,a$7))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:Ko,handleTool:r$1(Xo)},{key:"platform",tier:"advanced",getToolsList:ga,handleTool:r$1(fa)},{key:"pipeline",tier:"advanced",getToolsList:Wo,handleTool:r$1(zo)},{key:"graduation",tier:"advanced",getToolsList:yo,handleTool:r$1(ho)}]),s$1}function Gd(t,e){let s=g=>g.toLowerCase().replace(/\/+$/,""),n=s(t),r=s(e);if(n===r)return 1;let i=g=>!g.includes("/")&&g.includes("."),o=g=>i(g)?g.split("."):g.split("/").filter(Boolean),a=o(n),c=o(r);if(i(n)||i(r)){let g=i(n)?n.split("."):n.split("/").filter(Boolean),m=i(r)?r.split("."):r.split("/").filter(Boolean),y=0;for(let f=0;f<Math.min(g.length,m.length)&&g[f]===m[f];f++)y++;return y>0?Math.min(1,.5+y/Math.max(g.length,m.length)*.5):0}let l=0,d=Math.max(a.length,c.length);for(let g=0;g<d;g++){let m=a[g]||"",y=c[g]||"";m===y?l++:m.startsWith(":")&&y.startsWith(":")?l+=.9:m.startsWith(":")||y.startsWith(":")?l+=.7:(m.replace(/s$/,"")===y.replace(/s$/,"")||y.replace(/s$/,"")===m.replace(/s$/,""))&&(l+=.8);}let u=l/d,p=a.length===c.length?.1:0;return Math.min(1,u+p)}function Jd(){return [{name:"paradigm_search",description:"Search for Paradigm symbols by name, description, or tags. Includes fuzzy matching for typo tolerance. Returns matching symbols with names, paths, types, and descriptions. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query (matches symbol names, descriptions, tags)"},type:{type:"string",enum:["component","flow","gate","signal","aspect"],description:"Optional: filter by symbol type (v2: #component, $flow, ^gate, !signal, ~aspect)"},limit:{type:"number",description:"Maximum results to return (default: 10)"},fuzzy:{type:"boolean",description:"Enable fuzzy matching for typos (default: true)"},includeWorkspace:{type:"boolean",description:"Also search sibling workspace projects (default: false). Requires workspace configured in config.yaml."},componentType:{type:"string",description:'Filter components by type (e.g., "view", "service", "tool"). Only applies to #component symbols.'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["find","lookup","locate","where is","which symbol","find symbol"]},{name:"paradigm_related",description:"Get all symbols related to a given symbol. Call before modifying code to understand what uses this symbol and what it depends on. Returns uses/used-by lists with symbol types. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to find relations for"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_status",description:"Get project overview \u2014 call this at session start for orientation. Shows symbol counts, project health, and a pointer to the full capability guide. ~100 tokens.",inputSchema:{type:"object",properties:{response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["health","overview","dashboard","project status","orientation"]},{name:"paradigm_gates_for_route",description:"Suggest which gates should be applied to a route based on patterns in the project. Returns suggested gates with confidence scores and existing patterns. ~150 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:"Route path (e.g., /api/users, /admin/settings)"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["route"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["auth","permissions","route security","what gates","protect route"]},{name:"paradigm_plugin_check",description:"Check for updates to installed Claude Code plugins. Reports which marketplace clones have newer remote commits and which cached versions are stale.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_workspace_reindex",description:"Rebuild scan-index.json for all workspace members. Requires workspace configured in config.yaml. Returns per-member symbol counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_tool_activate",description:"Activate an advanced-tier tool module for this session. Advanced tools are not loaded by default to reduce tool count. Call with a feature key to make its tools available. ~50 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:'Feature key to activate (e.g., "graph", "heatmap", "pipeline", "conductor", "platform")'}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}function wf(t,e,s){let n$3=e(),r=Md(n$3.rootDir,s);t.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Jd(),...r.getActiveTools()]})),t.setRequestHandler(CallToolRequestSchema,async i=>{let{name:o$1,arguments:a}=i.params;Q(o$1,a??{});let c=e(),l$1=j();l$1.setRootDir(c.rootDir);let d=null,u=null;l$1.hasRecoveredThisSession()||(d=await T(c.rootDir),u=a$1(),b$2(),l$1.markRecovered());let p$1=await(async()=>{switch(o$1){case "paradigm_search":{let{query:g,type:m$1,limit:y=10,fuzzy:f=true,includeWorkspace:v=false,componentType:h$1,response_format:b}=a,w=`search:${g}:${m$1||""}:${y}:${f}:${v}:${h$1||""}`,x=await a$2.getOrCompute(w,()=>{let C=m(c.index,g);return m$1&&(C=C.filter(j=>j.type===m$1)),h$1&&(C=C.filter(j=>j.componentType===h$1)),C}),k=[];if(x.length===0&&f){let C=q(c.index),j=C.map(O=>O.symbol);k=Wa(g,j,{maxDistance:3,maxResults:5}),k.length>0&&(x=k.map(O=>C.find(R=>R.symbol===O.match)).filter(O=>O!=null),m$1&&(x=x.filter(O=>O.type===m$1)));}x=x.slice(0,y);let _={query:g,count:x.length,results:x.map(C=>({symbol:C.symbol,type:C.type,description:C.description,filePath:C.filePath,...C.componentType?{componentType:C.componentType}:{},...C.parentSymbol?{parentSymbol:C.parentSymbol}:{}}))};if(k.length>0&&(_.fuzzyMatched=true,_.fuzzyNote=`No exact matches for "${g}". Showing similar symbols.`,_.suggestions=k.map(C=>({symbol:C.match,distance:C.distance}))),v&&c.workspace){let C=h(c.workspace,g),j=m$1?C.filter(O=>O.type===m$1):C;j.length>0&&(_.workspaceResults=j.slice(0,y).map(O=>({symbol:O.symbol,type:O.type,description:O.description,filePath:O.filePath,project:O.project})),_.workspaceCount=j.length);}b==="concise"&&(_.results=x.map(C=>({symbol:C.symbol,type:C.type})),delete _.fuzzyMatched,delete _.fuzzyNote,delete _.suggestions,delete _.workspaceResults,delete _.workspaceCount);let T=JSON.stringify(_,null,2);return O(T.length,o$1),{content:[{type:"text",text:T}]}}case "paradigm_related":{let{symbol:g}=a,m=k(c.index,g);if(!m){let h=n$1(c.rootDir,g,{maxResults:20});if(h.length===0){let _=JSON.stringify({error:"Symbol not found",symbol:g,fallback:"searched",referencesFound:0,recovery:["Run `paradigm_search` with a partial name to find similar symbols","Check `.purpose` files for symbol definitions","Use `paradigm_status` to see available symbols by type","The symbol may not be indexed yet - run `paradigm scan`"]},null,2);return O(_.length,o$1),{content:[{type:"text",text:_}]}}let b=[...new Set(h.map(_=>_.filePath))],w=h.filter(_=>_.context==="purpose"),x=h.filter(_=>_.context==="code"),k=JSON.stringify({symbol:g,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:b.slice(0,10).map(_=>({file:_,references:h.filter(T=>T.filePath===_).length})),uses:[],summary:{totalFiles:b.length,totalReferences:h.length,purposeFileRefs:w.length,codeRefs:x.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return O(k.length,o$1),{content:[{type:"text",text:k}]}}let y=n$2(c.index,g),f=o(c.index,g),v=JSON.stringify({symbol:m.symbol,type:m.type,description:m.description,usedBy:y.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),uses:f.map(h=>({symbol:h.symbol,type:h.type,description:h.description}))},null,2);return O(v.length,o$1),{content:[{type:"text",text:v}]}}case "paradigm_status":{let g=a.response_format,m=await a$2.getOrCompute("status",async()=>{let f=p(c.index),v=Object.values(f).reduce((P,I)=>P+I,0),h={};for(let P of Object.keys(f)){let I=l(c.index,P);h[P]=I.slice(0,3).map(G=>G.symbol);}let b=Ni.platform(),w=b==="win32",x=w?"PowerShell/CMD":b==="darwin"?"zsh/bash":"bash",k;try{let P=await H$1(c.rootDir);P&&P.health.total>0&&(k=P.health);}catch{}let _=l(c.index,"component"),T={};for(let P of _)P.componentType&&(T[P.componentType]=(T[P.componentType]||0)+1);let C=_.filter(P=>!P.componentType).length,j;try{let{checkPurposeHealth:P}=await import('./integrity-checker-DHGMZQDG.js');j=P(c.aggregation.purposeFiles,c.rootDir).healthScore;}catch{}let O;try{let{countNotebookReferences:P}=await import('./session-work-log-T2IE4Y4T.js'),I=P(c.rootDir);I>0&&(O=I);}catch{}let R;try{let{getComplianceTrend:P,getHealthDot:I}=await import('./compliance-health-JNP3P35P.js'),G=P(c.rootDir);G&&(R={trend:G,dot:I(G,c.rootDir)});}catch{}return JSON.stringify({project:c.projectName,symbolSystem:"v2",counts:{"# components":f.component,"$ flows":f.flow,"^ gates":f.gate,"! signals":f.signal,"~ aspects":f.aspect},total:v,...Object.keys(T).length>0?{componentTypes:{...T,...C>0?{"(untyped)":C}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...j!==void 0?{purposeHealthScore:j}:{},...k?{protocols:k}:{},...O!==void 0?{notebookReferences:O}:{},...R?{complianceHealth:R}:{},capabilities:"paradigm://context/agent-protocol",...await(async()=>{try{let{loadArchMap:P}=await import('./arch-loader-G3AAM4E2.js'),I=P(c.rootDir);if(I)return {arch:{present:!0,tiers:I.tiers.length,links:I.links.length}}}catch{}return {}})(),note:"Symbol System v2: Use tags [feature], [state], [integration], [idea] for classification. Use type field for structural role (view, service, tool, etc.)",environment:{os:b,shell:x,terminalNote:w?"Use PowerShell syntax: semicolons for command chaining, backslashes for paths, $env:VAR for env vars":"Use Unix syntax: && for command chaining, forward slashes for paths, $VAR for env vars"}},null,2)}),y=m;if(g==="concise")try{let f=JSON.parse(m);y=JSON.stringify({project:f.project,counts:f.counts,total:f.total},null,2);}catch{}return O(y.length,o$1),{content:[{type:"text",text:y}]}}case "paradigm_gates_for_route":{let{route:g,response_format:m}=a,f=typeof g=="string"&&!g.includes("/")&&g.includes(".")?"POST":a.method||"GET",v=l(c.index,"gate"),h=[],b=[];if(c.gateConfig?.routes)for(let[R,P]of Object.entries(c.gateConfig.routes))P.gates&&b.push({route:R,gates:P.gates,method:P.method});if(c.workspace)for(let[R,P]of c.workspace.siblingIndices){let I=P.gateConfig;if(I?.routes)for(let[G,fe]of Object.entries(I.routes)){let rt=fe,br=Array.isArray(rt)?rt:rt?.gates;br&&b.push({route:G,gates:br,method:Array.isArray(rt)?void 0:rt?.method,source:R});}}for(let R of b){let P=Gd(g,R.route);if(P>=.6&&(!R.method||R.method===f))for(let I of R.gates){let G=v.find(fe=>fe.symbol===I||fe.symbol===`^${I}`);if(G&&!h.find(fe=>fe.gate===G.symbol)){let fe=R.source?`${R.source}/portal.yaml`:"portal.yaml";h.push({gate:G.symbol,reason:`Similar route "${R.route}" uses this gate`,confidence:P>=.8?"high":"medium",source:fe});}}}let k=g.split("/").filter(Boolean).find(R=>!R.startsWith(":")&&R!=="api")?.replace(/s$/,"")||"",_=g.match(/\/:(id|[a-z]+Id)($|\/)/i);if(_&&k){let R=v.find(P=>{let I=P.symbol.toLowerCase(),G=(P.description||"").toLowerCase();return I.includes(`${k}-owner`)||I.includes("owner")||I.includes("ownership")||G.includes("owner")||G.includes("ownership")||G.includes("belongs to")});R?h.push({gate:R.symbol,reason:`Resource ID route (${k}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${k}-owner`,reason:`Consider adding ownership gate for ${k} resource`,confidence:"medium"});}if(g.includes("/admin")||g.includes("/settings")){let R=v.find(P=>P.symbol.includes("admin")||P.description?.toLowerCase().includes("admin"));R&&h.push({gate:R.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(g.startsWith("/api/")||g.includes("/user")||g.includes("/account")){let R=v.find(P=>P.symbol.includes("authenticated")||P.symbol.includes("auth"));R&&h.push({gate:R.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(g.includes("/premium")||g.includes("/pro")||g.includes("/export")){let R=v.find(P=>P.symbol.includes("subscription")||P.symbol.includes("premium"));R&&h.push({gate:R.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(f==="DELETE"){let R=v.find(P=>P.symbol.includes("authenticated"));R&&!h.find(P=>P.gate===R.symbol)&&h.push({gate:R.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(f)){let R=v.find(P=>P.symbol.includes("authenticated"));R&&!h.find(P=>P.gate===R.symbol)&&h.push({gate:R.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let T=new Set,C=h.filter(R=>T.has(R.gate)?false:(T.add(R.gate),true)),j=m==="concise"?{suggestions:C.map(R=>({gate:R.gate,confidence:R.confidence}))}:{route:g,method:f,suggestions:C,availableGates:v.map(R=>({symbol:R.symbol,description:R.description})),note:_?"Resource ID routes should verify the user owns/has access to the specific resource.":"These are suggestions based on route patterns. Review your portal.yaml for exact requirements."},O$1=JSON.stringify(j,null,2);O(O$1.length,o$1);try{n(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:C.map(R=>R.gate),context:`Gate check for ${f} ${g}`});}catch{}return {content:[{type:"text",text:O$1}]}}case "paradigm_plugin_check":{let{runPluginUpdateCheck:g}=await import('./plugin-update-checker-M7PW434O.js'),m=await g(),y=m.filter(b=>b.hasRemoteUpdate||b.hasCacheStale);if(y.length===0){let b=m.length===0?"No Claude Code plugins found in ~/.claude/plugins/marketplaces/.":"All installed plugins are up to date.";return O(b.length,o$1),{content:[{type:"text",text:b}]}}let f=[`Plugin updates available:
131
+ `)}}case "paradigm_platform_clear":{let n=await Xe(s.projectDir,"clear",{target:e.target});return n.ok?{handled:true,text:`Cleared ${n.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${n.error}`}}default:return {handled:false,text:""}}}z$2();function ma(){return [{name:"paradigm_agent_list",description:"List all agent identity profiles with top expertise areas. Shows agents from both global (~/.paradigm/agents/) and project (.paradigm/agents/) scopes. Returns profile summaries with personality and top symbols. ~150 tokens.",inputSchema:{type:"object",properties:{scope:{type:"string",enum:["all","global","project"],description:"Filter by scope (default: all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_expertise",description:"Find which agents are best qualified to work on a specific symbol. Returns agents ranked by confidence score from their expertise history. Use for symbol-to-agent routing. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to query (e.g., "#auth-middleware", "$checkout-flow")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns only top agent (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_get",description:"Get full agent profile including personality, expertise table, transferable patterns, and per-project contexts. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID or nickname (e.g., "architect", "Apex", "Jinx")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_bench",description:"Bench an agent \u2014 Maestro will skip this agent during orchestration and nomination scoring. Use when an agent is noisy or unhelpful. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to bench (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_agent_activate",description:"Activate a benched agent \u2014 restore it to active Maestro orchestration. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to activate (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ya(t,e,s){switch(t){case "paradigm_agent_list":{let n=i$1(s.rootDir),r=b$9(s.rootDir);if(n.length===0)return {handled:true,text:JSON.stringify({count:0,agents:[],note:"No .agent profiles found. Create one with `paradigm agent create <id> --global` or via paradigm_agent_create."},null,2)};let i=r?n.filter(l=>r.includes(l.id)):n,o=r?n.length-i.length:0,a=i$2(s.rootDir),c=new Map(a.map(l=>[l.id,l]));return {handled:true,text:JSON.stringify({count:i.length,totalAvailable:n.length,...r?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:i.map(l=>{let d=c.get(l.id);return {id:l.id,role:l.role,nickname:l.nickname,personality:l.personality,...d?{lastSession:d.lastSession?.summary?.slice(0,100),lastSessionAge:d.lastSession?.date,pendingWork:d.pendingWork?.length||0,sessionsOnProject:d.sessionsOnProject||0}:{},topExpertise:(l.expertise||[]).sort((u,p)=>p.confidence-u.confidence).slice(0,5).map(u=>({symbol:u.symbol,confidence:parseFloat(u.confidence.toFixed(2)),sessions:u.sessions})),projectContexts:Object.keys(l.contexts||{}),transferableCount:(l.transferable||[]).length,...l.attention?.threshold!=null?{threshold:l.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let n=e.symbol,r=e.response_format,i=l$4(s.rootDir,n);return r==="concise"?{handled:true,text:JSON.stringify({symbol:n,topAgent:i.length>0?{id:i[0].agentId,confidence:parseFloat(i[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:n,agents:i.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:i.length,...i.length===0?{note:`No agents have recorded expertise on ${n}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let n=e.id,r=h$4(s.rootDir,n);if(!r){let o=i$1(s.rootDir),a=n.toLowerCase(),c=o.filter(l=>l.nickname?.toLowerCase().includes(a)||l.id.includes(a));return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found by ID or nickname`,...c.length>0?{didYouMean:c.map(l=>({id:l.id,nickname:l.nickname}))}:{suggestion:`Create with \`paradigm agent create ${n} --global\``}},null,2)}}let i=y$2(r);return {handled:true,text:JSON.stringify({id:r.id,role:r.role,description:r.description,version:r.version,personality:r.personality,expertise:(r.expertise||[]).sort((o,a)=>a.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(r.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:r.contexts,created:r.created,updated:r.updated,...r.permissions?{permissions:r.permissions}:{},integrity:i},null,2)}}case "paradigm_agent_bench":{let n=e.id,r=h$4(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let i=r.id,o=b$9(s.rootDir);return o?o=o.filter(a=>a!==i):o=e$6().filter(a=>a!==i),d$6(s.rootDir,o),{handled:true,text:JSON.stringify({id:i,...r.nickname?{nickname:r.nickname}:{},removedFromRoster:true,rosterCount:o.length,note:`${r.nickname||i} (${i}) removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let n=e.id,r=h$4(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let i=r.id,o=b$9(s.rootDir);return o&&(o.includes(i)||(o.push(i),d$6(s.rootDir,o))),{handled:true,text:JSON.stringify({id:i,...r.nickname?{nickname:r.nickname}:{},addedToRoster:true,rosterCount:o?.length??"all (no roster)",note:`${r.nickname||i} (${i}) is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}var va=$.join(".paradigm","authority.yaml");async function ha(t){let e=$.join(t,va),s;try{s=await Qe.readFile(e,"utf8");}catch(r){if(r.code==="ENOENT")return null;throw r}let n=qe.load(s);return n==null||typeof n!="object"?{version:"1.0",schema:"v0-experimental",claims:{}}:((!n.claims||typeof n.claims!="object")&&(n.claims={}),n)}async function ba(t,e){let s=$.join(t,va);await Qe.mkdir($.dirname(s),{recursive:true});let n=qe.dump(e,{lineWidth:100,sortKeys:false});await Qe.writeFile(s,n,"utf8");}function wa(){return [{name:"paradigm_authority_claim",description:"Claim authority over a scope in .paradigm/authority.yaml. Idempotent on `scope` \u2014 re-claiming overwrites severity/claimant. Single-claimant-per-scope at v6.1. Severity vocab: advise|warn|block (policy stance, distinct from remediation severity). ~100 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:'Archetype id (e.g., "compliance")'},scope:{type:"string",description:'Scope key (e.g., "aspect-coverage", "aspect-drift", "anchor-staleness")'},severity:{type:"string",enum:["advise","warn","block"],description:"Policy stance. Default: advise."}},required:["claimant","scope"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_authority_release",description:"Release authority over a scope. Removes the claim entry from .paradigm/authority.yaml. Succeeds on archetype-default-created scopes (user/agent can override defaults). ~80 tokens.",inputSchema:{type:"object",properties:{claimant:{type:"string",description:"Archetype id (used for audit; release is by scope key)"},scope:{type:"string",description:"Scope key to release"}},required:["claimant","scope"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function ka(t,e,s){if(t==="paradigm_authority_claim"){let n=e.claimant,r=e.scope,i=e.severity??"advise";if(!n||!r)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let o=new Date().toISOString(),a={claimant:n,severity:i,since:o,source:"explicit"},c=await ha(s.rootDir)??{version:"1.0",schema:"v0-experimental",claims:{}};return c.claims[r]=a,await ba(s.rootDir,c),{handled:true,text:JSON.stringify({scope:r,claimant:n,severity:i,source:"explicit",since:o},null,2)}}if(t==="paradigm_authority_release"){let n=e.claimant,r=e.scope;if(!n||!r)return {handled:true,text:JSON.stringify({error:"Missing required field: claimant, scope"},null,2)};let i=await ha(s.rootDir);if(!i||!(r in i.claims))return {handled:true,text:JSON.stringify({scope:r,released:false,note:"no active claim on this scope"},null,2)};let o=i.claims[r].claimant;return delete i.claims[r],await ba(s.rootDir,i),{handled:true,text:JSON.stringify({scope:r,released:true,previousClaimant:o},null,2)}}return {handled:false,text:""}}j();function _a(){return [{name:"paradigm_notebook_search",description:"Search agent notebook entries by concept, tag, or keyword. Notebooks are curated snippet libraries distilled from lore for reuse in orchestration. ~150 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:'Agent ID to search notebooks for (e.g., "architect", "builder")'},query:{type:"string",description:"Search query \u2014 matches concepts, tags, context, and snippet content"},concepts:{type:"array",items:{type:"string"},description:'Filter by concept tags (e.g., ["auth", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Filter by classification tags"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level (default: "detailed")'}},required:["agentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_notebook_add",description:"Add a new entry to an agent's notebook. Use for curated, reusable snippets that should be available across sessions. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add notebook entry for"},context:{type:"string",description:"When to apply this snippet \u2014 the retrieval context"},snippet:{type:"string",description:"The reusable code/knowledge snippet"},concepts:{type:"array",items:{type:"string"},description:'Concept tags for retrieval (e.g., ["auth", "jwt", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Classification tags"},confidence:{type:"number",description:"Confidence score 0.0-1.0 (default: 0.7)"},scope:{type:"string",enum:["global","project"],description:'Where to store: global travels across projects (default: "global")'},parentId:{type:"string",description:"Optional: ID of the parent notebook entry this was derived from (soft provenance, no validation)"},lineageType:{type:"string",enum:["fix","derive","capture","promote"],description:"Optional: relationship to parent \u2014 fix (corrects parent), derive (modified from parent), capture (new observation), promote (promoted from lower confidence)"}},required:["agentId","context","snippet","concepts"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_notebook_promote",description:"Extract a lore entry into a notebook entry. Distills the lore into a reusable snippet with provenance linking. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add the promoted entry to"},loreEntryId:{type:"string",description:'Lore entry ID to promote (e.g., "L-2026-03-15-...")'},scope:{type:"string",enum:["global","project"],description:'Where to store (default: "global")'}},required:["agentId","loreEntryId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Sa(t,e,s){switch(t){case "paradigm_notebook_search":{let n=e.agentId,r=e.query,i=e.concepts,o=e.tags,a=e.response_format,c;return r?c=e$7(n,r,s.rootDir):c=b$a(n,s.rootDir,{concepts:i,tags:o}),a==="concise"?{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,concepts:l.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,snippet:l.snippet.length>500?l.snippet.slice(0,500)+"...":l.snippet,concepts:l.concepts,tags:l.tags,appliedCount:l.appliedCount,confidence:l.confidence,provenance:l.provenance}))},null,2)}}case "paradigm_notebook_add":{let n=e.agentId,r=e.context,i=e.snippet,o=e.concepts||[],a=e.tags||[],c=e.confidence??.7,l=e.scope||(s.rootDir?"project":"global"),d=e.parentId,u=e.lineageType,p=e.publishable,g=e.scope,m={context:r,snippet:i,provenance:{source:"manual",createdBy:n},confidence:c,concepts:o,tags:a,...g?{scope:g}:{},...p!==void 0?{publishable:p}:{},...d?{parentId:d}:{},...u?{lineageType:u}:{}},y=g$3(n,m,l,s.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:y.entry.id,agentId:n,scope:l,filePath:y.filePath,concepts:y.entry.concepts,...d?{parentId:d}:{},...u?{lineageType:u}:{}},null,2)}}case "paradigm_notebook_promote":{let n=e.agentId,r=e.loreEntryId,i=e.scope||(s.rootDir?"project":"global"),o=await h$5(n,r,s.rootDir,i);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:n,loreEntryId:r,scope:i,publishScope:o.entry.scope,publishable:o.entry.publishable,filePath:o.filePath,concepts:o.entry.concepts,confidence:o.entry.confidence,note:o.entry.scope!=="generalizable"?`scope auto-classified as "${o.entry.scope}" \u2014 confirm or override with "nevr notebook audit"`:void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry "${r}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}var jd=".paradigm/scan-index.json",Od=".paradigm/flow-index.json",Ad=".paradigm/config.yaml",Id="portal.yaml",Dd=".paradigm/university/index.yaml",X={enabled:true,title:null,theme:"dark",customCss:null,customContent:"docs/",exclude:{tags:[],patterns:[]},sidebar:{collapsed:[]},output:".paradigm/docs-site"};function tt(t){let e=$.join(t,Ad);if(!I.existsSync(e))return {...X};try{let s=I.readFileSync(e,"utf8"),n=qe.load(s);if(!n||!n.docs)return {...X};let r=n.docs;return {enabled:r.enabled??X.enabled,title:r.title??X.title,theme:r.theme??X.theme,customCss:r.customCss??X.customCss,customContent:r.customContent??X.customContent,exclude:{tags:r.exclude?.tags??X.exclude.tags,patterns:r.exclude?.patterns??X.exclude.patterns},sidebar:{collapsed:r.sidebar?.collapsed??X.sidebar.collapsed},output:r.output??X.output}}catch{return {...X}}}function en(t){let e=$.join(t,jd);if(!I.existsSync(e))return null;try{let s=I.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function yr(t){let e=$.join(t,Od);if(!I.existsSync(e))return null;try{let s=I.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function tn(t){let e=$.join(t,Id);if(!I.existsSync(e))return null;try{let s=I.readFileSync(e,"utf8");return qe.load(s)}catch{return null}}function Ca(t){let e=$.join(t,Dd);if(!I.existsSync(e))return null;try{let s=I.readFileSync(e,"utf8");return qe.load(s)}catch{return null}}function Ra(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:qe.load(e[1]),body:e[2].trim()}}catch{return null}}function Ta(t){let e=new Map,s=[t.components,t.features,t.flows,t.state,t.gates,t.signals,t.aspects];for(let n of s)if(n)for(let[r,i]of Object.entries(n))e.set(r,i);return e}function $d(t){return {components:"component",features:"component",flows:"flow",state:"component",gates:"gate",signals:"signal",aspects:"aspect"}[t]||"component"}function et(t,e){if(e.exclude.tags.length>0&&t.visualTags){for(let s of t.visualTags)if(e.exclude.tags.includes(s))return true}if(e.exclude.patterns.length>0&&t.path){for(let s of e.exclude.patterns)if(s.endsWith("*")){let n=s.slice(0,-1);if(t.path.includes(n))return true}else if(t.path.includes(s))return true}return false}function Pa(t,e){let s=$.join(t,e);if(!I.existsSync(s))return [];let n=[];try{let r=I.readdirSync(s).filter(i=>i.endsWith(".md"));for(let i of r)try{let o=I.readFileSync($.join(s,i),"utf8"),a=i.replace(/\.md$/,""),c=Ra(o);c?n.push({slug:a,title:c.frontmatter.title||a,body:c.body,order:typeof c.frontmatter.order=="number"?c.frontmatter.order:void 0,description:c.frontmatter.description||void 0}):n.push({slug:a,title:a,body:o.trim()});}catch{}}catch{}return n.sort((r,i)=>r.order!=null&&i.order!=null?r.order-i.order:r.order!=null?-1:i.order!=null?1:r.title.localeCompare(i.title)),n}function ja(t,e,s){let n=s||tt(t),r=$.join(t,n.customContent),i=$.join(r,`${e}.md`);if(!I.existsSync(i))return null;try{let o=I.readFileSync(i,"utf8"),a=Ra(o);return a?{slug:e,title:a.frontmatter.title||e,body:a.body,order:typeof a.frontmatter.order=="number"?a.frontmatter.order:void 0,description:a.frontmatter.description||void 0}:{slug:e,title:e,body:o.trim()}}catch{return null}}function Oa(t,e){let s=e||tt(t),n=en(t),r=yr(t),i=tn(t),o=Pa(t,s.customContent),a=Ca(t),c=n?.$meta?.project||$.basename(t),l=s.title||`${c} Docs`,d=[],u={},p=0;if(o.length>0&&d.push({id:"custom-pages",label:"Pages",collapsed:s.sidebar.collapsed.includes("custom-pages"),items:o.map(g=>({id:g.slug,label:g.title,kind:"custom",description:g.description}))}),a&&a.entries.length>0){let g=a.entries.filter(m=>(m.type==="note"||m.type==="policy")&&m.symbols.length>0);g.length>0&&d.push({id:"guides",label:"Guides",collapsed:s.sidebar.collapsed.includes("guides"),items:g.map(m=>({id:m.id,label:m.title,kind:"guide",description:void 0,badge:m.symbols.length>0?`${m.symbols.length} symbols`:void 0}))});}if(n){let g=Object.values(n.components||{}).filter(k=>!et(k,s));if(g.length>0){let k=new Map;for(let C of g){let j=C.componentType||"other";k.has(j)||k.set(j,[]),k.get(j).push(C);}let P=[...k.entries()].sort((C,j)=>j[1].length-C[1].length).map(([C,j])=>({id:`components-${C}`,label:`${C.charAt(0).toUpperCase()+C.slice(1)} (${j.length})`,collapsed:s.sidebar.collapsed.includes(`components-${C}`),items:j.sort((O,R)=>O.name.localeCompare(R.name)).map(O=>({id:O.id,label:O.name,kind:"component",description:O.description,badge:O.componentType}))}));d.push({id:"components",label:`Components (${g.length})`,collapsed:s.sidebar.collapsed.includes("components"),items:[],subgroups:P}),u.components=g.length,p+=g.length;}let m=Object.values(n.features||{}).filter(k=>!et(k,s));m.length>0&&(d.push({id:"features",label:`Features (${m.length})`,collapsed:s.sidebar.collapsed.includes("features"),items:m.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"component",description:k.description}))}),u.features=m.length,p+=m.length);let y=Object.values(n.flows||{}).filter(k=>!et(k,s)),f=new Set(y.map(k=>k.id)),v=[];if(r)for(let[k,_]of Object.entries(r.flows)){let P=k.replace(/^\$/,"");f.has(P)||v.push({id:P,label:_.name||P,kind:"flow",description:_.description});}let h=[...y.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"flow",description:k.description})),...v];h.length>0&&(d.push({id:"flows",label:`Flows (${h.length})`,collapsed:s.sidebar.collapsed.includes("flows"),items:h}),u.flows=h.length,p+=h.length);let b=Object.values(n.gates||{}).filter(k=>!et(k,s));b.length>0&&(d.push({id:"gates",label:`Gates (${b.length})`,collapsed:s.sidebar.collapsed.includes("gates"),items:b.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"gate",description:k.description}))}),u.gates=b.length,p+=b.length);let w=Object.values(n.signals||{}).filter(k=>!et(k,s));w.length>0&&(d.push({id:"signals",label:`Signals (${w.length})`,collapsed:s.sidebar.collapsed.includes("signals"),items:w.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"signal",description:k.description}))}),u.signals=w.length,p+=w.length);let x=Object.values(n.aspects||{}).filter(k=>!et(k,s));x.length>0&&(d.push({id:"aspects",label:`Aspects (${x.length})`,collapsed:s.sidebar.collapsed.includes("aspects"),items:x.sort((k,_)=>k.name.localeCompare(_.name)).map(k=>({id:k.id,label:k.name,kind:"aspect",description:k.description}))}),u.aspects=x.length,p+=x.length);}if(i){let g=Object.keys(i.routes||{}).length,m=Object.keys(i.gates||{}).length;d.push({id:"portal",label:"Portal",collapsed:s.sidebar.collapsed.includes("portal"),items:[{id:"portal-overview",label:"Authorization Overview",kind:"portal",description:`${m} gates, ${g} routes`,badge:`${g} routes`}]});}return {title:l,project:c,generatedAt:new Date().toISOString(),groups:d,totalSymbols:p,symbolCounts:u}}function Aa(t,e){let s=en(t);if(!s)return null;let n=Ta(s),r=n.get(e);if(!r)return null;let i=[];for(let[f,v]of n)f!==e&&v.related&&v.related.includes(r.symbol)&&i.push(v.symbol);let o=(r.related||[]).slice(),a=[],c=yr(t);if(c)for(let[f,v]of Object.entries(c.flows)){let h=(v.steps||[]).map(b=>b.symbol);(h.includes(r.symbol)||h.includes(`#${e}`))&&a.push({id:f.replace(/^\$/,""),name:v.name||f});}if(s.flows)for(let[f,v]of Object.entries(s.flows)){if(a.some(b=>b.id===f))continue;let h=(v.steps||[]).map(b=>b.symbol).filter(Boolean);(h.includes(r.symbol)||h.includes(`#${e}`))&&a.push({id:f,name:v.name});}let l=[],d=tn(t);if(d&&r.category==="gates"){let f=Object.keys(d.gates||{}).find(v=>v.replace(/^\^/,"")===e);f&&l.push({id:f.replace(/^\^/,""),description:d.gates[f].description});}else if(d){let f=new Set((r.related||[]).filter(v=>v.startsWith("^")));for(let[v,h]of Object.entries(d.routes||{}))for(let b of h){let w=b.replace(/^\^/,"");if(f.has(b)||f.has(`^${w}`)){let x=d.gates[b]||d.gates[`^${w}`]||d.gates[w];x&&!l.some(k=>k.id===w)&&l.push({id:w,description:x.description});}}}let u=[];if(s.aspects)for(let[f,v]of Object.entries(s.aspects))v.related&&v.related.includes(r.symbol)&&u.push(v.symbol);for(let f of r.related||[])f.startsWith("~")&&!u.includes(f)&&u.push(f);let p=[],g=Ca(t);if(g)for(let f of g.entries)f.symbols.includes(r.symbol)&&p.push({id:f.id,title:f.title});let m=r.parent||void 0,y=[];if(s.components)for(let f of Object.values(s.components))f.parent===r.symbol&&y.push(f.symbol);return {id:r.id,symbol:r.symbol,name:r.name,description:r.description||"",category:r.category||"components",componentType:r.componentType,tags:r.visualTags||[],path:r.path||"",related:r.related||[],referencedBy:i,references:o,flows:a,gates:l,aspects:u,guides:p,parent:m,children:y}}function Ia(t,e){let s=yr(t),n=en(t);if(s){let r=s.flows[`$${e}`]?`$${e}`:e,i=s.flows[r];if(i){let o=(i.steps||[]).map(c=>({type:c.type||"action",symbol:c.symbol||"",description:c.description})),a=n?.flows?.[e.replace(/^\$/,"")];return {id:e.replace(/^\$/,""),symbol:`$${e.replace(/^\$/,"")}`,name:i.name||e,description:i.description,trigger:i.trigger,steps:o,successSignal:i.successSignal,errorSignal:i.errorSignal,tags:a?.visualTags||[],path:a?.path||i.definedIn||""}}}if(n?.flows){let r=e.replace(/^\$/,""),i=n.flows[r];if(i){let o=(i.steps||[]).map(a=>({type:"action",symbol:a.symbol||"",description:a.action||a.name}));return {id:r,symbol:`$${r}`,name:i.name,description:i.description,steps:o,tags:i.visualTags||[],path:i.path||""}}}return null}function Da(t){let e=tn(t);if(!e)return {version:"0",gates:[],routes:[]};let s=new Map;for(let[i,o]of Object.entries(e.routes||{}))for(let a of o){let c=a.replace(/^\^/,"");s.has(c)||s.set(c,[]),s.get(c).push(i);}let n=Object.entries(e.gates||{}).map(([i,o])=>{let a=i.replace(/^\^/,"");return {symbol:`^${a}`,description:o.description,check:o.check,routes:s.get(a)||[]}}),r=Object.entries(e.routes||{}).map(([i,o])=>{let a=i.indexOf(" "),c=a>0?i.substring(0,a):"GET";return {route:a>0?i.substring(a+1):i,method:c,gates:o.map(d=>{let u=d.replace(/^\^/,""),p=e.gates[d]||e.gates[`^${u}`]||e.gates[u];return {symbol:`^${u}`,description:p?.description}})}});return {version:e.version||"1.0",gates:n,routes:r}}function $a(t,e,s){let n=s||20,r=[],i=e.toLowerCase(),o=en(t);if(o){let d=Ta(o);for(let[u,p]of d){let g=mr(p.name,p.description||"",p.visualTags||[],i);g>0&&r.push({id:p.id,kind:$d(p.category),label:p.name,description:p.description||"",matchContext:xa(p.name,p.description||"",i),score:g});}}let a=tt(t),c=Pa(t,a.customContent);for(let d of c){let u=d.body.substring(0,200),p=mr(d.title,u,[],i);p>0&&r.push({id:d.slug,kind:"custom",label:d.title,description:d.description||u.substring(0,100),matchContext:xa(d.title,d.body,i),score:p});}let l=tn(t);if(l)for(let[d,u]of Object.entries(l.gates||{})){let p=d.replace(/^\^/,""),g=mr(p,u.description,[],i);g>0&&r.push({id:p,kind:"portal",label:`^${p}`,description:u.description,score:g});}return r.sort((d,u)=>u.score-d.score||d.label.localeCompare(u.label)),r.slice(0,n)}function mr(t,e,s,n){let r=t.toLowerCase(),i=e.toLowerCase();return r===n?1:r.startsWith(n)?.8:r.includes(n)?.6:i.includes(n)?.5:s.some(o=>o.toLowerCase().includes(n))?.3:0}function xa(t,e,s){let r=e.toLowerCase().indexOf(s);if(r<0)return t.toLowerCase().includes(s)?t:void 0;let i=Math.max(0,r-40),o=Math.min(e.length,r+s.length+40),a=e.substring(i,o).trim();return i>0&&(a=`...${a}`),o<e.length&&(a=`${a}...`),a}function Ha(){return [{name:"paradigm_docs_manifest",description:"Get the documentation sidebar manifest \u2014 all symbols grouped by type with counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_page",description:"Get page data for a symbol, flow, portal, or custom docs page. Returns structured data for rendering. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol ID (e.g., "cli-commands", "checkout-flow", "authenticated"). Do not include the prefix (#, $, ^, !, ~).'},flow:{type:"string",description:'Flow ID (e.g., "$init-flow"). Include the $ prefix.'},portal:{type:"boolean",description:"Set to true to get the portal overview page (gates + routes)."},slug:{type:"string",description:'Custom page slug (e.g., "getting-started").'}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_search",description:"Search across all documentation content \u2014 symbols, descriptions, tags, custom pages. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query string"},limit:{type:"number",description:"Maximum results (default: 20)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Fa(t,e,s){if(t==="paradigm_docs_manifest"){let n=tt(s.rootDir),r=Oa(s.rootDir,n),i=JSON.stringify(r,null,2);return O(i.length,t),{handled:true,text:i}}if(t==="paradigm_docs_page"){if(e.portal){let r=Da(s.rootDir),i=JSON.stringify(r,null,2);return O(i.length,t),{handled:true,text:i}}if(e.flow){let r=e.flow,i=Ia(s.rootDir,r);if(!i){let a=JSON.stringify({error:`Flow "${r}" not found`});return O(a.length,t),{handled:true,text:a}}let o=JSON.stringify(i,null,2);return O(o.length,t),{handled:true,text:o}}if(e.slug){let r=tt(s.rootDir),i=ja(s.rootDir,e.slug,r);if(!i){let a=JSON.stringify({error:`Page "${e.slug}" not found`});return O(a.length,t),{handled:true,text:a}}let o=JSON.stringify(i,null,2);return O(o.length,t),{handled:true,text:o}}if(e.symbol){let r=Aa(s.rootDir,e.symbol);if(!r){let o=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return O(o.length,t),{handled:true,text:o}}let i=JSON.stringify(r,null,2);return O(i.length,t),{handled:true,text:i}}let n=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return O(n.length,t),{handled:true,text:n}}if(t==="paradigm_docs_search"){let n=e.query;if(!n)return {handled:true,text:JSON.stringify({error:"query is required"})};let r=$a(s.rootDir,n,e.limit),i=JSON.stringify({count:r.length,results:r},null,2);return O(i.length,t),{handled:true,text:i}}return {handled:false,text:""}}f();e();function Na(){return [{name:"paradigm_work_log_record",description:"Record a work log entry \u2014 what got done. Auto-attached to sprint boards and standup summaries. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent that did the work (e.g., "builder")'},summary:{type:"string",description:"What was done"},outcome:{type:"string",enum:["pass","fail","partial","blocked"],description:"How it went"},task_ref:{type:"string",description:'Ticket/issue reference (e.g., "ENG-142")'},files_modified:{type:"array",items:{type:"string"},description:"Files that were modified"},symbols_touched:{type:"array",items:{type:"string"},description:"Paradigm symbols touched"},next_steps:{type:"array",items:{type:"string"},description:"What's left to do"},blockers:{type:"array",items:{type:"string"},description:"What's blocking progress"},duration_minutes:{type:"number",description:"How long it took"},commit:{type:"string",description:"Git commit hash"}},required:["agent","summary","outcome"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_work_log_search",description:"Search work log entries \u2014 what got done. Returns recent work, filterable by agent, outcome, symbol, date. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent"},outcome:{type:"string",enum:["pass","fail","partial","blocked"]},task_ref:{type:"string",description:"Filter by ticket reference"},symbol:{type:"string",description:"Filter by symbol touched"},dateFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},dateTo:{type:"string",description:"End date (YYYY-MM-DD)"},limit:{type:"number",description:"Max entries to return (default 20)"},summary:{type:"boolean",description:"Return aggregate summary instead of entries"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_journal_record",description:"Record a learning journal entry \u2014 what an agent learned. Agent-private, travels across projects. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent who learned this (e.g., "security")'},trigger:{type:"string",enum:["correction_received","confidence_miss","pattern_discovered","debate_loss","failure_analysis","human_feedback","self_reflection"],description:"What triggered this learning moment"},insight:{type:"string",description:"The insight itself"},project:{type:"string",description:"Project where this happened"},transferable:{type:"boolean",description:"Whether this applies to other projects"},confidence_before:{type:"number",description:"Confidence before (0.0-1.0)"},confidence_after:{type:"number",description:"Confidence after (0.0-1.0)"},pattern:{type:"object",properties:{id:{type:"string"},applies_when:{type:"string"},correct_approach:{type:"string"}}},linked_work_log:{type:"string",description:"Work log entry that prompted this"},tags:{type:"array",items:{type:"string"}}},required:["agent","trigger","insight","project","transferable"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_journal_search",description:"Search learning journal entries \u2014 what agents learned. Can search across all agents or a specific one. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent (omit for all agents)"},trigger:{type:"string",description:"Filter by trigger type"},project:{type:"string",description:"Filter by project"},transferable:{type:"boolean",description:"Only show transferable insights"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},stats:{type:"boolean",description:"Return stats instead of entries (requires agent)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_decision_record",description:"Record a team decision \u2014 what we decided and why. Institutional memory with rationale and alternatives. ~100 tokens.",inputSchema:{type:"object",properties:{title:{type:"string",description:"Decision title"},decision:{type:"string",description:"The decision itself"},rationale:{type:"string",description:"Why this was chosen"},participants:{type:"array",items:{type:"object",properties:{id:{type:"string"},role:{type:"string",enum:["human","agent"]},stance:{type:"string",enum:["proposed","supported","dissented","abstained","neutral"]}},required:["id","role","stance"]}},alternatives_considered:{type:"array",items:{type:"object",properties:{option:{type:"string"},rejected_because:{type:"string"}}}},symbols_affected:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","proposed"],description:"Decision status (default: active)"},tags:{type:"array",items:{type:"string"}}},required:["title","decision","rationale","participants"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_decision_search",description:"Search team decisions \u2014 what we decided. Find active decisions by symbol, participant, status. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["active","superseded","deprecated","proposed","rejected"]},participant:{type:"string",description:"Filter by participant ID"},symbol:{type:"string",description:"Filter by affected symbol"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},summary:{type:"boolean",description:"Return aggregate summary"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ea(t,e,s){let n=r=>JSON.stringify(r,null,2);switch(t){case "paradigm_work_log_record":{let r=c$3(s.rootDir),{filtered:i}=d(e.summary,r,"work_log"),o=a$9(s.rootDir,{agent:e.agent,summary:i,outcome:e.outcome,task_ref:e.task_ref,files_modified:e.files_modified,symbols_touched:e.symbols_touched,next_steps:e.next_steps,blockers:e.blockers,duration_minutes:e.duration_minutes,commit:e.commit});return {text:n({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let i=d$3(s.rootDir,7);return {text:n(i),handled:true}}let r=b$7(s.rootDir,{agent:e.agent,outcome:e.outcome,task_ref:e.task_ref,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:r.length,entries:r.map(i=>({id:i.id,agent:i.agent,summary:i.summary,outcome:i.outcome,timestamp:i.timestamp,symbols_touched:i.symbols_touched,task_ref:i.task_ref}))}),handled:true}}case "paradigm_journal_record":{let r=c$3(s.rootDir),{filtered:i}=d(e.insight,r,"learning_journal"),o=a$8(e.agent,{trigger:e.trigger,insight:i,project:e.project,transferable:e.transferable,confidence_before:e.confidence_before,confidence_after:e.confidence_after,pattern:e.pattern,linked_work_log:e.linked_work_log,tags:e.tags});return {text:n({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let i=e$3(e.agent);return {text:n(i),handled:true}}let r=e.agent?b$6(e.agent,{trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}):d$2({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:r.length,entries:r.map(i=>({id:i.id,agent:i.agent,trigger:i.trigger,insight:i.insight.slice(0,200),project:i.project,transferable:i.transferable,timestamp:i.timestamp}))}),handled:true}}case "paradigm_decision_record":{let r=c$3(s.rootDir),{filtered:i}=d(e.decision,r,"team_decisions"),{filtered:o}=d(e.rationale,r,"team_decisions"),a=a$7(s.rootDir,{title:e.title,decision:i,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags}),c=d$1(s.rootDir,a.id);return {text:n({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp,...c?{companion_lore_id:c}:{}}),handled:true}}case "paradigm_decision_search":{if(e.summary){let i=h$1(s.rootDir);return {text:n(i),handled:true}}let r=e$2(s.rootDir,{status:e.status,participant:e.participant,symbol:e.symbol,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:r.length,entries:r.map(i=>({id:i.id,title:i.title,status:i.status,decision:i.decision.slice(0,200),participants:i.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:i.symbols_affected,timestamp:i.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${t}`,handled:false}}}var kt=["purpose-coverage","purpose-exists","portal-gates","aspect-anchors","purpose-freshness","aspect-advisory","lore-required","habits-blocking","purpose-required-patterns","drift-detection","portal-compliance","graduation-tracking","orchestration-required"],qa={strict:{"purpose-coverage":"block","purpose-exists":"block","portal-gates":"block","aspect-anchors":"block","purpose-freshness":"warn","aspect-advisory":"warn","lore-required":"block","habits-blocking":"block","purpose-required-patterns":"block","drift-detection":"block","portal-compliance":"block","graduation-tracking":"warn","orchestration-required":"block"},balanced:{"purpose-coverage":"block","purpose-exists":"warn","portal-gates":"warn","aspect-anchors":"warn","purpose-freshness":"warn","aspect-advisory":"off","lore-required":"warn","habits-blocking":"block","purpose-required-patterns":"warn","drift-detection":"warn","portal-compliance":"warn","graduation-tracking":"off","orchestration-required":"warn"},minimal:{"purpose-coverage":"warn","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"warn","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"},none:{"purpose-coverage":"off","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"off","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"}};function nn(t){let e=$.join(t,".paradigm","config.yaml");if(!I.existsSync(e))return {};try{return qe.load(I.readFileSync(e,"utf8"))||{}}catch{return {}}}function hr(t,e){let s=$.join(t,".paradigm","config.yaml");I.writeFileSync(s,qe.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function rn(t){let e=t.enforcement?.level||"none",s=qa[e]||qa.none,n=t.enforcement?.checks||{},r=t.enforcement?.orchestration?.threshold??3,i={...s};for(let[o,a]of Object.entries(n))kt.includes(o)&&La(a)&&(i[o]=a);return i.orchestrationThreshold=r,i}function La(t){return t==="block"||t==="warn"||t==="off"}function Hd(t){return t==="strict"||t==="balanced"||t==="minimal"||t==="none"}function Fd(t){return kt.includes(t)}var Nd=[{name:"paradigm_compliance_promote",description:"Record a user's response to Rune's enforcement-level promotion offer. Call this after presenting the symbol-tracking invitation. Response 'minimal' or 'balanced' enables enforcement at that level and records the promotion state; 'snooze' defers for 7 days; 'never' suppresses the offer permanently.",inputSchema:{type:"object",properties:{response:{type:"string",enum:["minimal","balanced","snooze","never"],description:"User's chosen response to the promotion offer"}},required:["response"]}},{name:"paradigm_enforcement_configure",description:"View or modify stop hook enforcement levels. Actions: status (view current), set-level (change preset), override (set per-check severity), reset (clear overrides). ~250 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["status","set-level","override","reset"],description:"Action to perform."},level:{type:"string",enum:["strict","balanced","minimal","none"],description:"Enforcement preset level (for set-level action)."},checkId:{type:"string",description:"Check ID to override (for override action). One of: "+kt.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function Ed(t,e){let{action:s,level:n,checkId:r,severity:i}=e;switch(s){case "status":{let o=nn(t.rootDir),a=rn(o),c=o.enforcement?.level||"none",l=o.enforcement?.checks||{},d=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:c,orchestrationThreshold:d,orchestrationNote:"Threshold is compared against magnitude score (not just file count). Magnitude = source files + cross-package penalty + security-adjacent penalty + symbol file changes.",overrides:Object.keys(l).length>0?l:void 0,effective:a,checkIds:[...kt],presetLevels:["strict","balanced","minimal","none"]},null,2)}case "set-level":{if(!n||!Hd(n))return JSON.stringify({error:`Invalid level "${n}". Must be one of: strict, balanced, minimal, none`});let o=nn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=n,o.enforcement.checks={},hr(t.rootDir,o);let a=rn(o);return JSON.stringify({success:true,level:n,message:`Enforcement level set to "${n}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!r||!Fd(r))return JSON.stringify({error:`Invalid checkId "${r}". Must be one of: ${kt.join(", ")}`});if(!i||!La(i))return JSON.stringify({error:`Invalid severity "${i}". Must be one of: block, warn, off`});let o=nn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[r]=i,hr(t.rootDir,o);let a=rn(o);return JSON.stringify({success:true,checkId:r,severity:i,message:`Override set: ${r} = ${i}`,effective:a},null,2)}case "reset":{let o=nn(t.rootDir);o.enforcement&&(o.enforcement.checks={}),hr(t.rootDir,o);let a=rn(o),c=o.enforcement?.level||"none";return JSON.stringify({success:true,message:`All per-check overrides cleared. Preset "${c}" is now fully in effect.`,effective:a},null,2)}default:return JSON.stringify({error:`Unknown action "${s}". Must be one of: status, set-level, override, reset`})}}function Ma(){return Nd}async function Ga(t,e,s){if(t==="paradigm_enforcement_configure"){let n=await Ed(s,e);return O(n.length,"paradigm_enforcement_configure"),{handled:true,text:n}}if(t==="paradigm_compliance_promote"){let n=e.response,{recordPromotion:r}=await import('./rune-promotion-3JQ5LMWK.js');r(s.rootDir,n);let i;if(n==="minimal"||n==="balanced"){let o=$.join(s.rootDir,".paradigm","config.yaml");if(I.existsSync(o)){let a=qe.load(I.readFileSync(o,"utf8"));a&&typeof a=="object"&&((!a.enforcement||typeof a.enforcement!="object")&&(a.enforcement={}),a.enforcement.level=n,I.writeFileSync(o,qe.dump(a,{lineWidth:-1,noRefs:true,sortKeys:false}),"utf8"));}i=JSON.stringify({ok:true,message:`Symbol tracking enabled at "${n}". Rune is now active.`,level:n});}else n==="snooze"?i=JSON.stringify({ok:true,message:"Got it \u2014 I'll ask again in 7 days.",state:"snoozed"}):i=JSON.stringify({ok:true,message:"Understood. I won't bring this up again.",state:"never"});return O(i.length,"paradigm_compliance_promote"),{handled:true,text:i}}return {handled:false,text:""}}b$1();function Ja(){return [{name:"paradigm_arch_status",description:"Get the architectural layer map summary and drift report. Shows tiers, their components, and any symbols that are unassigned (not in any tier) or missing from the index. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_arch_diagram",description:"Render the architectural map as a Mermaid diagram. Returns a Mermaid graph TD string showing tiers and their links. ~150 tokens.",inputSchema:{type:"object",properties:{format:{type:"string",enum:["mermaid"],description:'Output format. Only "mermaid" supported (default: "mermaid").'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Ua(t,e,s){try{if(t==="paradigm_arch_status"){let n=b$b(s.rootDir);if(!n)return {text:JSON.stringify({exists:!1,message:"No arch.yaml found. Create .paradigm/arch.yaml to start mapping your architecture."}),handled:!0};let r=d$7(s.rootDir,s);return {text:JSON.stringify({exists:!0,version:n.version,tierCount:n.tiers.length,tiers:n.tiers.map(i=>({id:i.id,label:i.label,responsibility:i.responsibility,framework:i.tech?.framework??"",componentCount:i.components.length,components:i.components})),links:n.links,drift:{unassigned:r.unassigned,missing_purpose:r.missing_purpose,clean:r.unassigned.length===0&&r.missing_purpose.length===0}}),handled:!0}}if(t==="paradigm_arch_diagram"){let n=b$b(s.rootDir);if(!n)return {text:JSON.stringify({error:"No arch.yaml found. Cannot render diagram."}),handled:!0};let r=e$8(n);return {text:JSON.stringify({format:"mermaid",diagram:r}),handled:!0}}return {handled:!1,text:""}}catch(n){return a.component("#arch-tools").warn(`Unexpected error in arch tool ${t}`,{error:String(n)}),{text:JSON.stringify({error:String(n)}),handled:true}}}function qd(t,e){let s=[];for(let n=0;n<=e.length;n++)s[n]=[n];for(let n=0;n<=t.length;n++)s[0][n]=n;for(let n=1;n<=e.length;n++)for(let r=1;r<=t.length;r++)e.charAt(n-1)===t.charAt(r-1)?s[n][r]=s[n-1][r-1]:s[n][r]=Math.min(s[n-1][r-1]+1,s[n][r-1]+1,s[n-1][r]+1);return s[e.length][t.length]}function Wa(t,e,s={}){let{maxDistance:n=3,maxResults:r=5}=s,i=t.toLowerCase(),o=[];for(let a of e){let c=a.toLowerCase();if(c===i){o.push({match:a,distance:0});continue}if(c.includes(i)||i.includes(c)){o.push({match:a,distance:1});continue}let l=qd(i,c);l<=n&&o.push({match:a,distance:l});}return o.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:a.match.localeCompare(c.match)),o.slice(0,r)}v();function Gd(t$1,e){let s$1=new a$3(t$1),n=e||(async()=>{}),r$1=o=>async(a,c,l)=>o(a,c,l),i=o=>async(a,c,l)=>o(a,c,l,n);return s$1.registerAll([{key:"context",tier:"core",getToolsList:R,handleTool:r$1(S)},{key:"navigate",tier:"core",getToolsList:l$1,handleTool:r$1(m$1)},{key:"tags",tier:"core",getToolsList:Hi,handleTool:r$1(Fi)},{key:"purpose-portal",tier:"core",getToolsList:Ui,handleTool:i(Wi)},{key:"pm",tier:"core",getToolsList:ao,handleTool:r$1(co)},{key:"reindex",tier:"core",getToolsList:n$3,handleTool:i(o$1)},{key:"docs",tier:"core",getToolsList:Ha,handleTool:r$1(Fa)},{key:"ripple",tier:"core",getToolsList:q$1,handleTool:r$1(r)},{key:"captain",tier:"core",getToolsList:C,handleTool:r$1(D)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:s,handleTool:r$1(t)},{key:"history",tier:"feature",getToolsList:_i,handleTool:r$1(Si)},{key:"lore",tier:"feature",getToolsList:A,handleTool:r$1(B)},{key:"streams",tier:"feature",getToolsList:Na,handleTool:r$1(Ea)},{key:"ambient",tier:"feature",getToolsList:a$4,handleTool:r$1(b$4)},{key:"sentinel",tier:"feature",getToolsList:xi,handleTool:r$1(Ci)},{key:"flows",tier:"feature",getToolsList:Ri,handleTool:r$1(Ti)},{key:"fixtures",tier:"feature",getToolsList:Ii,handleTool:r$1(Di)},{key:"orchestration",tier:"feature",getToolsList:b$3,handleTool:r$1(c$1)},{key:"habits",tier:"feature",getToolsList:po,handleTool:r$1(uo)},{key:"tasks",tier:"feature",getToolsList:Co,handleTool:r$1(Ro)},{key:"personas",tier:"feature",getToolsList:Fo,handleTool:r$1(No)},{key:"protocols",tier:"feature",getToolsList:u,handleTool:r$1(v$1)},{key:"symphony",tier:"feature",getToolsList:Zo,handleTool:r$1(ea)},{key:"university",tier:"feature",getToolsList:pa,handleTool:r$1(ua)},{key:"agents",tier:"feature",getToolsList:ma,handleTool:r$1(ya)},{key:"authority",tier:"feature",getToolsList:wa,handleTool:r$1(ka)},{key:"propose-block",tier:"feature",getToolsList:a$5,handleTool:r$1(b$5)},{key:"notebooks",tier:"feature",getToolsList:_a,handleTool:r$1(Sa)},{key:"aspect-graph",tier:"feature",getToolsList:So,handleTool:r$1(xo)},{key:"enforcement",tier:"feature",getToolsList:Ma,handleTool:r$1(Ga),detect:o=>I.existsSync($.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Lo,handleTool:r$1(Mo),detect:o=>I.existsSync($.join(o,".paradigm","aspect-graph.db"))},{key:"arch",tier:"feature",getToolsList:Ja,handleTool:r$1(Ua),detect:o=>I.existsSync($.join(o,a$6))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:Ko,handleTool:r$1(Xo)},{key:"platform",tier:"advanced",getToolsList:ga,handleTool:r$1(fa)},{key:"pipeline",tier:"advanced",getToolsList:Wo,handleTool:r$1(zo)},{key:"graduation",tier:"advanced",getToolsList:yo,handleTool:r$1(ho)}]),s$1}function Jd(t,e){let s=g=>g.toLowerCase().replace(/\/+$/,""),n=s(t),r=s(e);if(n===r)return 1;let i=g=>!g.includes("/")&&g.includes("."),o=g=>i(g)?g.split("."):g.split("/").filter(Boolean),a=o(n),c=o(r);if(i(n)||i(r)){let g=i(n)?n.split("."):n.split("/").filter(Boolean),m=i(r)?r.split("."):r.split("/").filter(Boolean),y=0;for(let f=0;f<Math.min(g.length,m.length)&&g[f]===m[f];f++)y++;return y>0?Math.min(1,.5+y/Math.max(g.length,m.length)*.5):0}let l=0,d=Math.max(a.length,c.length);for(let g=0;g<d;g++){let m=a[g]||"",y=c[g]||"";m===y?l++:m.startsWith(":")&&y.startsWith(":")?l+=.9:m.startsWith(":")||y.startsWith(":")?l+=.7:(m.replace(/s$/,"")===y.replace(/s$/,"")||y.replace(/s$/,"")===m.replace(/s$/,""))&&(l+=.8);}let u=l/d,p=a.length===c.length?.1:0;return Math.min(1,u+p)}function Ud(){return [{name:"paradigm_search",description:"Search for Paradigm symbols by name, description, or tags. Includes fuzzy matching for typo tolerance. Returns matching symbols with names, paths, types, and descriptions. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query (matches symbol names, descriptions, tags)"},type:{type:"string",enum:["component","flow","gate","signal","aspect"],description:"Optional: filter by symbol type (v2: #component, $flow, ^gate, !signal, ~aspect)"},limit:{type:"number",description:"Maximum results to return (default: 10)"},fuzzy:{type:"boolean",description:"Enable fuzzy matching for typos (default: true)"},includeWorkspace:{type:"boolean",description:"Also search sibling workspace projects (default: false). Requires workspace configured in config.yaml."},componentType:{type:"string",description:'Filter components by type (e.g., "view", "service", "tool"). Only applies to #component symbols.'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["find","lookup","locate","where is","which symbol","find symbol"]},{name:"paradigm_related",description:"Get all symbols related to a given symbol. Call before modifying code to understand what uses this symbol and what it depends on. Returns uses/used-by lists with symbol types. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to find relations for"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_status",description:"Get project overview \u2014 call this at session start for orientation. Shows symbol counts, project health, and a pointer to the full capability guide. ~100 tokens.",inputSchema:{type:"object",properties:{response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["health","overview","dashboard","project status","orientation"]},{name:"paradigm_gates_for_route",description:"Suggest which gates should be applied to a route based on patterns in the project. Returns suggested gates with confidence scores and existing patterns. ~150 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:"Route path (e.g., /api/users, /admin/settings)"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["route"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["auth","permissions","route security","what gates","protect route"]},{name:"paradigm_plugin_check",description:"Check for updates to installed Claude Code plugins. Reports which marketplace clones have newer remote commits and which cached versions are stale.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_workspace_reindex",description:"Rebuild scan-index.json for all workspace members. Requires workspace configured in config.yaml. Returns per-member symbol counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_tool_activate",description:"Activate an advanced-tier tool module for this session. Advanced tools are not loaded by default to reduce tool count. Call with a feature key to make its tools available. ~50 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:'Feature key to activate (e.g., "graph", "heatmap", "pipeline", "conductor", "platform")'}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}function _f(t,e,s){let n$3=e(),r=Gd(n$3.rootDir,s);t.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Ud(),...r.getActiveTools()]})),t.setRequestHandler(CallToolRequestSchema,async i=>{let{name:o$1,arguments:a}=i.params;Q(o$1,a??{});let c=e(),l$1=j$1();l$1.setRootDir(c.rootDir);let d=null,u=null;l$1.hasRecoveredThisSession()||(d=await T(c.rootDir),u=a$1(),b$2(),l$1.markRecovered());let p$1=await(async()=>{switch(o$1){case "paradigm_search":{let{query:g,type:m$1,limit:y=10,fuzzy:f=true,includeWorkspace:v=false,componentType:h$1,response_format:b}=a,w=`search:${g}:${m$1||""}:${y}:${f}:${v}:${h$1||""}`,x=await a$2.getOrCompute(w,()=>{let C=m(c.index,g);return m$1&&(C=C.filter(j=>j.type===m$1)),h$1&&(C=C.filter(j=>j.componentType===h$1)),C}),k=[];if(x.length===0&&f){let C=q(c.index),j=C.map(O=>O.symbol);k=Wa(g,j,{maxDistance:3,maxResults:5}),k.length>0&&(x=k.map(O=>C.find(R=>R.symbol===O.match)).filter(O=>O!=null),m$1&&(x=x.filter(O=>O.type===m$1)));}x=x.slice(0,y);let _={query:g,count:x.length,results:x.map(C=>({symbol:C.symbol,type:C.type,description:C.description,filePath:C.filePath,...C.componentType?{componentType:C.componentType}:{},...C.parentSymbol?{parentSymbol:C.parentSymbol}:{}}))};if(k.length>0&&(_.fuzzyMatched=true,_.fuzzyNote=`No exact matches for "${g}". Showing similar symbols.`,_.suggestions=k.map(C=>({symbol:C.match,distance:C.distance}))),v&&c.workspace){let C=h(c.workspace,g),j=m$1?C.filter(O=>O.type===m$1):C;j.length>0&&(_.workspaceResults=j.slice(0,y).map(O=>({symbol:O.symbol,type:O.type,description:O.description,filePath:O.filePath,project:O.project})),_.workspaceCount=j.length);}b==="concise"&&(_.results=x.map(C=>({symbol:C.symbol,type:C.type})),delete _.fuzzyMatched,delete _.fuzzyNote,delete _.suggestions,delete _.workspaceResults,delete _.workspaceCount);let P=JSON.stringify(_,null,2);return O(P.length,o$1),{content:[{type:"text",text:P}]}}case "paradigm_related":{let{symbol:g}=a,m=k(c.index,g);if(!m){let h=n$1(c.rootDir,g,{maxResults:20});if(h.length===0){let _=JSON.stringify({error:"Symbol not found",symbol:g,fallback:"searched",referencesFound:0,recovery:["Run `paradigm_search` with a partial name to find similar symbols","Check `.purpose` files for symbol definitions","Use `paradigm_status` to see available symbols by type","The symbol may not be indexed yet - run `paradigm scan`"]},null,2);return O(_.length,o$1),{content:[{type:"text",text:_}]}}let b=[...new Set(h.map(_=>_.filePath))],w=h.filter(_=>_.context==="purpose"),x=h.filter(_=>_.context==="code"),k=JSON.stringify({symbol:g,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:b.slice(0,10).map(_=>({file:_,references:h.filter(P=>P.filePath===_).length})),uses:[],summary:{totalFiles:b.length,totalReferences:h.length,purposeFileRefs:w.length,codeRefs:x.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return O(k.length,o$1),{content:[{type:"text",text:k}]}}let y=n$2(c.index,g),f=o(c.index,g),v=JSON.stringify({symbol:m.symbol,type:m.type,description:m.description,usedBy:y.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),uses:f.map(h=>({symbol:h.symbol,type:h.type,description:h.description}))},null,2);return O(v.length,o$1),{content:[{type:"text",text:v}]}}case "paradigm_status":{let g=a.response_format,m=await a$2.getOrCompute("status",async()=>{let f=p(c.index),v=Object.values(f).reduce((T,D)=>T+D,0),h={};for(let T of Object.keys(f)){let D=l(c.index,T);h[T]=D.slice(0,3).map(G=>G.symbol);}let b=Ni.platform(),w=b==="win32",x=w?"PowerShell/CMD":b==="darwin"?"zsh/bash":"bash",k;try{let T=await H$1(c.rootDir);T&&T.health.total>0&&(k=T.health);}catch{}let _=l(c.index,"component"),P={};for(let T of _)T.componentType&&(P[T.componentType]=(P[T.componentType]||0)+1);let C=_.filter(T=>!T.componentType).length,j;try{let{checkPurposeHealth:T}=await import('./integrity-checker-DHGMZQDG.js');j=T(c.aggregation.purposeFiles,c.rootDir).healthScore;}catch{}let O;try{let{countNotebookReferences:T}=await import('./session-work-log-T2IE4Y4T.js'),D=T(c.rootDir);D>0&&(O=D);}catch{}let R;try{let{getComplianceTrend:T,getHealthDot:D}=await import('./compliance-health-JNP3P35P.js'),G=T(c.rootDir);G&&(R={trend:G,dot:D(G,c.rootDir)});}catch{}return JSON.stringify({project:c.projectName,symbolSystem:"v2",counts:{"# components":f.component,"$ flows":f.flow,"^ gates":f.gate,"! signals":f.signal,"~ aspects":f.aspect},total:v,...Object.keys(P).length>0?{componentTypes:{...P,...C>0?{"(untyped)":C}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...j!==void 0?{purposeHealthScore:j}:{},...k?{protocols:k}:{},...O!==void 0?{notebookReferences:O}:{},...R?{complianceHealth:R}:{},capabilities:"paradigm://context/agent-protocol",...await(async()=>{try{let{loadArchMap:T}=await import('./arch-loader-G3AAM4E2.js'),D=T(c.rootDir);if(D)return {arch:{present:!0,tiers:D.tiers.length,links:D.links.length}}}catch{}return {}})(),note:"Symbol System v2: Use tags [feature], [state], [integration], [idea] for classification. Use type field for structural role (view, service, tool, etc.)",environment:{os:b,shell:x,terminalNote:w?"Use PowerShell syntax: semicolons for command chaining, backslashes for paths, $env:VAR for env vars":"Use Unix syntax: && for command chaining, forward slashes for paths, $VAR for env vars"}},null,2)}),y=m;if(g==="concise")try{let f=JSON.parse(m);y=JSON.stringify({project:f.project,counts:f.counts,total:f.total},null,2);}catch{}return O(y.length,o$1),{content:[{type:"text",text:y}]}}case "paradigm_gates_for_route":{let{route:g,response_format:m}=a,f=typeof g=="string"&&!g.includes("/")&&g.includes(".")?"POST":a.method||"GET",v=l(c.index,"gate"),h=[],b=[];if(c.gateConfig?.routes)for(let[R,T]of Object.entries(c.gateConfig.routes))T.gates&&b.push({route:R,gates:T.gates,method:T.method});if(c.workspace)for(let[R,T]of c.workspace.siblingIndices){let D=T.gateConfig;if(D?.routes)for(let[G,fe]of Object.entries(D.routes)){let rt=fe,br=Array.isArray(rt)?rt:rt?.gates;br&&b.push({route:G,gates:br,method:Array.isArray(rt)?void 0:rt?.method,source:R});}}for(let R of b){let T=Jd(g,R.route);if(T>=.6&&(!R.method||R.method===f))for(let D of R.gates){let G=v.find(fe=>fe.symbol===D||fe.symbol===`^${D}`);if(G&&!h.find(fe=>fe.gate===G.symbol)){let fe=R.source?`${R.source}/portal.yaml`:"portal.yaml";h.push({gate:G.symbol,reason:`Similar route "${R.route}" uses this gate`,confidence:T>=.8?"high":"medium",source:fe});}}}let k=g.split("/").filter(Boolean).find(R=>!R.startsWith(":")&&R!=="api")?.replace(/s$/,"")||"",_=g.match(/\/:(id|[a-z]+Id)($|\/)/i);if(_&&k){let R=v.find(T=>{let D=T.symbol.toLowerCase(),G=(T.description||"").toLowerCase();return D.includes(`${k}-owner`)||D.includes("owner")||D.includes("ownership")||G.includes("owner")||G.includes("ownership")||G.includes("belongs to")});R?h.push({gate:R.symbol,reason:`Resource ID route (${k}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${k}-owner`,reason:`Consider adding ownership gate for ${k} resource`,confidence:"medium"});}if(g.includes("/admin")||g.includes("/settings")){let R=v.find(T=>T.symbol.includes("admin")||T.description?.toLowerCase().includes("admin"));R&&h.push({gate:R.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(g.startsWith("/api/")||g.includes("/user")||g.includes("/account")){let R=v.find(T=>T.symbol.includes("authenticated")||T.symbol.includes("auth"));R&&h.push({gate:R.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(g.includes("/premium")||g.includes("/pro")||g.includes("/export")){let R=v.find(T=>T.symbol.includes("subscription")||T.symbol.includes("premium"));R&&h.push({gate:R.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(f==="DELETE"){let R=v.find(T=>T.symbol.includes("authenticated"));R&&!h.find(T=>T.gate===R.symbol)&&h.push({gate:R.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(f)){let R=v.find(T=>T.symbol.includes("authenticated"));R&&!h.find(T=>T.gate===R.symbol)&&h.push({gate:R.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let P=new Set,C=h.filter(R=>P.has(R.gate)?false:(P.add(R.gate),true)),j=m==="concise"?{suggestions:C.map(R=>({gate:R.gate,confidence:R.confidence}))}:{route:g,method:f,suggestions:C,availableGates:v.map(R=>({symbol:R.symbol,description:R.description})),note:_?"Resource ID routes should verify the user owns/has access to the specific resource.":"These are suggestions based on route patterns. Review your portal.yaml for exact requirements."},O$1=JSON.stringify(j,null,2);O(O$1.length,o$1);try{n(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:C.map(R=>R.gate),context:`Gate check for ${f} ${g}`});}catch{}return {content:[{type:"text",text:O$1}]}}case "paradigm_plugin_check":{let{runPluginUpdateCheck:g}=await import('./plugin-update-checker-M7PW434O.js'),m=await g(),y=m.filter(b=>b.hasRemoteUpdate||b.hasCacheStale);if(y.length===0){let b=m.length===0?"No Claude Code plugins found in ~/.claude/plugins/marketplaces/.":"All installed plugins are up to date.";return O(b.length,o$1),{content:[{type:"text",text:b}]}}let f=[`Plugin updates available:
132
132
  `],v=[];for(let b of y)b.hasRemoteUpdate?(f.push(` ${b.plugin} (${b.repo}): remote has newer commits`),v.push(`git -C ${b.marketplacePath} pull origin main`)):b.hasCacheStale&&f.push(` ${b.plugin} (${b.repo}): ${b.installedVersion} \u2192 ${b.localVersion} (restart needed)`);v.length>0?(f.push(`
133
133
  Update command:
134
134
  ${v.join(` && \\
135
135
  `)}`),f.push(`
136
136
  After running, restart the session to apply updates.`)):f.push(`
137
137
  Restart the session to apply cached updates.`);let h=f.join(`
138
- `);return O(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.workspace){let f=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return O(f.length,o$1),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:g}=await import('./reindex-XTRF23F7.js'),m=[];for(let f of c.workspace.config.members){let v=$.resolve($.dirname(c.workspace.workspacePath),f.path);try{let h=await g(v);m.push({name:f.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){m.push({name:f.name,symbolCount:0,status:`error: ${h.message}`});}}let y=JSON.stringify({action:"workspace_reindex",workspace:c.workspace.config.name,members:m,totalSymbols:m.reduce((f,v)=>f+v.symbolCount,0)},null,2);return O(y.length,o$1),a$2.clear(),{content:[{type:"text",text:y}]}}case "paradigm_tool_activate":{let g=a.feature,m=r.activateAdvanced(g);if(m){let h=JSON.stringify({action:"tool_activate",feature:g,status:"activated",toolsAdded:m.map(b=>b.name),note:`Advanced module "${g}" activated for this session. ${m.length} tool(s) now available.`},null,2);return O(h.length,o$1),{content:[{type:"text",text:h}]}}let y=r.getRegistryInfo(),f=y.activeFeatures.includes(g),v=JSON.stringify({action:"tool_activate",feature:g,status:f?"already_active":"not_found",note:f?`Module "${g}" is already active (auto-detected or core tier).`:`Module "${g}" not found. Available advanced modules: ${y.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:y.availableAdvanced},null,2);return O(v.length,o$1),{content:[{type:"text",text:v}]}}default:{let g=await r.dispatch(o$1,a,c);if(g&&g.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||O(g.text.length,o$1),Ud(o$1,a,c.rootDir),{content:[{type:"text",text:g.text}]};throw new Error(`Unknown tool: ${o$1}`)}}})();if(d||u){let g=p$1.content?.[0];if(g&&typeof g=="object"&&"text"in g&&typeof g.text=="string"){let m=[u,d].filter(Boolean).join(`
138
+ `);return O(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.workspace){let f=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return O(f.length,o$1),{content:[{type:"text",text:f}]}}let{rebuildStaticFiles:g}=await import('./reindex-ZLDQBFUR.js'),m=[];for(let f of c.workspace.config.members){let v=$.resolve($.dirname(c.workspace.workspacePath),f.path);try{let h=await g(v);m.push({name:f.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){m.push({name:f.name,symbolCount:0,status:`error: ${h.message}`});}}let y=JSON.stringify({action:"workspace_reindex",workspace:c.workspace.config.name,members:m,totalSymbols:m.reduce((f,v)=>f+v.symbolCount,0)},null,2);return O(y.length,o$1),a$2.clear(),{content:[{type:"text",text:y}]}}case "paradigm_tool_activate":{let g=a.feature,m=r.activateAdvanced(g);if(m){let h=JSON.stringify({action:"tool_activate",feature:g,status:"activated",toolsAdded:m.map(b=>b.name),note:`Advanced module "${g}" activated for this session. ${m.length} tool(s) now available.`},null,2);return O(h.length,o$1),{content:[{type:"text",text:h}]}}let y=r.getRegistryInfo(),f=y.activeFeatures.includes(g),v=JSON.stringify({action:"tool_activate",feature:g,status:f?"already_active":"not_found",note:f?`Module "${g}" is already active (auto-detected or core tier).`:`Module "${g}" not found. Available advanced modules: ${y.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:y.availableAdvanced},null,2);return O(v.length,o$1),{content:[{type:"text",text:v}]}}default:{let g=await r.dispatch(o$1,a,c);if(g&&g.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||O(g.text.length,o$1),Wd(o$1,a,c.rootDir),{content:[{type:"text",text:g.text}]};throw new Error(`Unknown tool: ${o$1}`)}}})();if(d||u){let g=p$1.content?.[0];if(g&&typeof g=="object"&&"text"in g&&typeof g.text=="string"){let m=[u,d].filter(Boolean).join(`
139
139
 
140
140
  `);g.text=m+`
141
141
 
142
- `+g.text;}}return p$1});}function Ud(t,e,s){try{switch(t){case "paradigm_sentinel_record":n(s,{type:"error-encountered",source:"mcp-tool-call",tool:t,severity:e.severity||"warning",context:`Sentinel: ${e.title||e.summary||"incident recorded"}`});break;case "paradigm_lore_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols_touched)?e.symbols_touched.map(String):[],context:`Lore recorded: ${e.title||"untitled"}`});break;case "paradigm_work_log_record":case "paradigm_journal_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Work logged: ${e.summary||e.title||"entry"}`});break;case "paradigm_decision_record":n(s,{type:"decision-made",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Decision: ${e.title||e.summary||"recorded"}`});break;case "paradigm_persona_run":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Persona run: ${e.persona||"unknown"}`});break;case "paradigm_protocol_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Protocol recorded: ${e.name||e.id||"unknown"}`});break;case "paradigm_reindex":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:"Index rebuilt"},{skipNominations:!0});break;default:(t.startsWith("paradigm_purpose_")||t.startsWith("paradigm_portal_"))&&(t.includes("_add_")||t.includes("_update_")||t.includes("_remove_"))&&n(s,{type:"file-modified",source:"mcp-tool-call",tool:t,symbols:e.id?[`#${e.id}`]:e.symbol?[String(e.symbol)]:[],context:`Purpose/portal update via ${t}`});break}}catch{}}export{xu as a,wf as b};
142
+ `+g.text;}}return p$1});}function Wd(t,e,s){try{switch(t){case "paradigm_sentinel_record":n(s,{type:"error-encountered",source:"mcp-tool-call",tool:t,severity:e.severity||"warning",context:`Sentinel: ${e.title||e.summary||"incident recorded"}`});break;case "paradigm_lore_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols_touched)?e.symbols_touched.map(String):[],context:`Lore recorded: ${e.title||"untitled"}`});break;case "paradigm_work_log_record":case "paradigm_journal_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Work logged: ${e.summary||e.title||"entry"}`});break;case "paradigm_decision_record":n(s,{type:"decision-made",source:"mcp-tool-call",tool:t,symbols:Array.isArray(e.symbols)?e.symbols.map(String):[],context:`Decision: ${e.title||e.summary||"recorded"}`});break;case "paradigm_persona_run":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Persona run: ${e.persona||"unknown"}`});break;case "paradigm_protocol_record":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:`Protocol recorded: ${e.name||e.id||"unknown"}`});break;case "paradigm_reindex":n(s,{type:"work-completed",source:"mcp-tool-call",tool:t,context:"Index rebuilt"},{skipNominations:!0});break;default:(t.startsWith("paradigm_purpose_")||t.startsWith("paradigm_portal_"))&&(t.includes("_add_")||t.includes("_update_")||t.includes("_remove_"))&&n(s,{type:"file-modified",source:"mcp-tool-call",tool:t,symbols:e.id?[`#${e.id}`]:e.symbol?[String(e.symbol)]:[],context:`Purpose/portal update via ${t}`});break}}catch{}}export{Cu as a,_f as b};