@a-company/paradigm 7.3.0 → 7.5.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 (115) hide show
  1. package/dist/{accept-orchestration-JA3A3TSU.js → accept-orchestration-NFNY5A4Q.js} +1 -1
  2. package/dist/{aggregate-H7SB2UYT.js → aggregate-647KIGV6.js} +1 -1
  3. package/dist/ambient-5TA5CD7Z.js +2 -0
  4. package/dist/{ambient-TFLZFV5Y.js → ambient-N24SR3BC.js} +1 -1
  5. package/dist/ambient-W3SPKLKC.js +2 -0
  6. package/dist/{arch-loader-YVOS3QRY.js → arch-loader-6TDQOSUE.js} +1 -1
  7. package/dist/arch-loader-NAGXLWUQ.js +2 -0
  8. package/dist/{beacon-WVN264OT.js → beacon-4XQSMTNN.js} +1 -1
  9. package/dist/captain-2MEKZKJS.js +2 -0
  10. package/dist/captain-V5XPN4UP.js +2 -0
  11. package/dist/{chunk-IBKCMLOW.js → chunk-43H6PB2A.js} +27 -27
  12. package/dist/chunk-54C2PETP.js +12 -0
  13. package/dist/{chunk-RGSFU2YW.js → chunk-5LIE2QMS.js} +1 -1
  14. package/dist/{chunk-ACJWUOMA.js → chunk-74NGU6YN.js} +1 -1
  15. package/dist/chunk-ABHILQLA.js +42 -0
  16. package/dist/{chunk-VR2LLUYE.js → chunk-AMZ3ESAK.js} +2 -2
  17. package/dist/chunk-BTMT4K73.js +93 -0
  18. package/dist/{chunk-MBKTVQS2.js → chunk-BXKFSYIN.js} +1 -1
  19. package/dist/chunk-CHFY3JSF.js +504 -0
  20. package/dist/chunk-D2T5AV5N.js +504 -0
  21. package/dist/{chunk-6VZSOQ7Y.js → chunk-DQ4MMMTP.js} +1 -1
  22. package/dist/chunk-F3OBFUOE.js +2 -0
  23. package/dist/chunk-GADXREYG.js +18 -0
  24. package/dist/{chunk-A5EEY6NO.js → chunk-HGT7RNOL.js} +1 -1
  25. package/dist/chunk-HLPYCWE5.js +6 -0
  26. package/dist/chunk-IGB2CIMK.js +93 -0
  27. package/dist/{chunk-27EK3OQZ.js → chunk-JJ3AUHQU.js} +1 -1
  28. package/dist/chunk-JOHPASZG.js +4 -0
  29. package/dist/{chunk-7BZPDOOQ.js → chunk-JOWT6J4C.js} +4 -4
  30. package/dist/chunk-L4MKNG56.js +42 -0
  31. package/dist/chunk-PRZZL57E.js +7 -0
  32. package/dist/{chunk-SD3KVW5Q.js → chunk-QBIME67A.js} +1 -1
  33. package/dist/{chunk-KA6QEI3C.js → chunk-QTMJVEEW.js} +1 -1
  34. package/dist/chunk-SGLIPRIC.js +3 -0
  35. package/dist/chunk-SOVBBLFK.js +6 -0
  36. package/dist/{chunk-VKVVIN6J.js → chunk-SPU3R5GW.js} +4 -4
  37. package/dist/{chunk-YNFF7XHV.js → chunk-T577TTVG.js} +2 -2
  38. package/dist/{chunk-3F4QP2Z5.js → chunk-VHVUJGZ2.js} +2 -2
  39. package/dist/chunk-WUSTIEYA.js +4 -0
  40. package/dist/{commands-4ENQMHFO.js → commands-RSHKXKXN.js} +1 -1
  41. package/dist/{compliance-3M6COUCO.js → compliance-EFNXWHDL.js} +1 -1
  42. package/dist/{constellation-TIKNCZWR.js → constellation-26225R5K.js} +1 -1
  43. package/dist/{diff-NZSJW3V3.js → diff-G52RYZNF.js} +1 -1
  44. package/dist/dist-N4NYCS3D.js +2 -0
  45. package/dist/dist-O7KGTIYK.js +4 -0
  46. package/dist/{docs-DWU3T2BV.js → docs-2O7HUSBX.js} +1 -1
  47. package/dist/doctor-KGQXLGOQ.js +2 -0
  48. package/dist/graph-slice-2WECDOEN.js +2 -0
  49. package/dist/index.js +5 -5
  50. package/dist/{init-QPMLEQWQ.js → init-JGYCABZZ.js} +1 -1
  51. package/dist/{integrity-FRGF5BFS.js → integrity-YUCXTQX3.js} +1 -1
  52. package/dist/mcp.js +2 -2
  53. package/dist/nomination-engine-3EYXJOZZ.js +2 -0
  54. package/dist/nomination-engine-BUPERVPR.js +2 -0
  55. package/dist/notebook-loader-QM4KUT4R.js +2 -0
  56. package/dist/{orchestrate-C7SI4J7C.js → orchestrate-RIKQB2DV.js} +1 -1
  57. package/dist/{orchestration-S2ESNKSA.js → orchestration-GFNPCEUU.js} +1 -1
  58. package/dist/orchestration-I62QXOWV.js +2 -0
  59. package/dist/{platform-server-IOWHNS7Q.js → platform-server-AAEDDBS3.js} +2 -2
  60. package/dist/{probe-G3TKOJYW.js → probe-GD3VDWGT.js} +1 -1
  61. package/dist/reindex-FNL4QRUZ.js +2 -0
  62. package/dist/reindex-N4NTDLJY.js +2 -0
  63. package/dist/{review-WHRNLW2W.js → review-YG4LWV22.js} +1 -1
  64. package/dist/{ripple-B6U7263T.js → ripple-S6VBP5C6.js} +1 -1
  65. package/dist/sentinel.js +1 -1
  66. package/dist/{serve-PWAFVYYC.js → serve-NPRYOGQX.js} +1 -1
  67. package/dist/session-tracker-HYN6ZYPH.js +2 -0
  68. package/dist/{session-work-log-T2IE4Y4T.js → session-work-log-KZX4PGUL.js} +1 -1
  69. package/dist/{setup-L5OP24US.js → setup-GPOTHS3N.js} +1 -1
  70. package/dist/{shift-HGXZ5THV.js → shift-ZIJTQ5SW.js} +2 -2
  71. package/dist/{snapshot-MT5L6XE4.js → snapshot-2ARNF3U2.js} +1 -1
  72. package/dist/{status-4QGKLOP6.js → status-NTWWESOR.js} +1 -1
  73. package/dist/{summary-6QNVQZJV.js → summary-4QXYLXAB.js} +1 -1
  74. package/dist/{sync-layer-C2PF273N.js → sync-layer-Z266WBWF.js} +1 -1
  75. package/dist/{task-PRLQ4VPK.js → task-6F527BNU.js} +1 -1
  76. package/dist/{task-loader-EIXPKHA3.js → task-loader-75NBBLRQ.js} +1 -1
  77. package/dist/{task-loader-LFEE6OU7.js → task-loader-INPLZRG5.js} +1 -1
  78. package/dist/{task-settlement-ZXOY4YGX.js → task-settlement-3ROAHAND.js} +2 -2
  79. package/dist/{task-settlement-A2T6EACG.js → task-settlement-F7CIKUG3.js} +2 -2
  80. package/dist/{team-KP4HMUB5.js → team-PFJTOCPM.js} +1 -1
  81. package/dist/tools-MAH6K5UL.js +142 -0
  82. package/dist/tools-Z354SXGS.js +2 -0
  83. package/dist/{workspace-4D4TQ637.js → workspace-HADUT5XT.js} +1 -1
  84. package/package.json +2 -1
  85. package/dist/ambient-OW5M5LVN.js +0 -2
  86. package/dist/ambient-VCTUHHIG.js +0 -2
  87. package/dist/arch-loader-G3AAM4E2.js +0 -2
  88. package/dist/captain-ILBN2IKJ.js +0 -2
  89. package/dist/captain-J4FZ5PRU.js +0 -2
  90. package/dist/chunk-33ERV2MW.js +0 -18
  91. package/dist/chunk-5VR7FKS5.js +0 -93
  92. package/dist/chunk-7HUPVOAY.js +0 -504
  93. package/dist/chunk-D6BSCELB.js +0 -2
  94. package/dist/chunk-FG3M6VVO.js +0 -30
  95. package/dist/chunk-HSY75GRR.js +0 -6
  96. package/dist/chunk-KAUGQMXU.js +0 -4
  97. package/dist/chunk-L3AOKDMU.js +0 -93
  98. package/dist/chunk-O4ADSTSY.js +0 -504
  99. package/dist/chunk-RVXQNS6K.js +0 -30
  100. package/dist/chunk-TMDPDIWA.js +0 -3
  101. package/dist/chunk-XBK244QR.js +0 -6
  102. package/dist/chunk-Y76OIMDO.js +0 -7
  103. package/dist/chunk-ZSWXLFN7.js +0 -12
  104. package/dist/dist-PW5YPGFF.js +0 -2
  105. package/dist/dist-RXYJK7AZ.js +0 -2
  106. package/dist/doctor-CBZYYQQH.js +0 -2
  107. package/dist/nomination-engine-EFXDEPZN.js +0 -2
  108. package/dist/nomination-engine-YRHZZZUN.js +0 -2
  109. package/dist/notebook-loader-TZVIMNDJ.js +0 -2
  110. package/dist/orchestration-4MJKBSGM.js +0 -2
  111. package/dist/reindex-G2JLIGOQ.js +0 -2
  112. package/dist/reindex-JR3PXYQE.js +0 -2
  113. package/dist/session-tracker-BZ7FU4AT.js +0 -2
  114. package/dist/tools-NOMEIBS7.js +0 -2
  115. package/dist/tools-YW3Q27UI.js +0 -142
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import*as j from'fs';import*as z from'js-yaml';import {z as z$1}from'zod';import*as P from'path';import {glob}from'glob';var B=z$1.object({description:z$1.string(),type:z$1.string().optional(),parent:z$1.string().optional(),anchors:z$1.array(z$1.string()).optional(),tags:z$1.array(z$1.string()).optional(),endpoints:z$1.array(z$1.string()).optional(),tests:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),aspects:z$1.array(z$1.string()).optional(),flows:z$1.array(z$1.string()).optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),states:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),location:z$1.string().optional(),locations:z$1.array(z$1.string()).optional(),uses:z$1.array(z$1.string()).optional(),"used-by":z$1.array(z$1.string()).optional(),"used-for":z$1.array(z$1.string()).optional(),exports:z$1.array(z$1.string()).optional(),status:z$1.string().optional(),properties:z$1.record(z$1.unknown()).optional(),handles:z$1.array(z$1.string()).optional()}).passthrough(),Z=B.extend({id:z$1.string()}),Pe=z$1.object({description:z$1.string().optional(),category:z$1.string().optional(),severity:z$1.enum(["info","warn","error"]).optional(),emitters:z$1.array(z$1.string()).optional(),related:z$1.array(z$1.string()).optional(),data:z$1.record(z$1.unknown()).optional()}),ke=z$1.union([Pe,z$1.string().transform(e=>({description:e}))]),Ce=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),Ae=z$1.union([Ce,z$1.string()]),je=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),ee=z$1.union([je,z$1.string()]),Ie=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(ee)}),De=z$1.object({description:z$1.string().optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),steps:z$1.array(ee).optional()}),Re=z$1.object({description:z$1.string().optional(),requires:z$1.array(z$1.string()).optional(),keys:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional()}),Ee=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),Fe=z$1.object({description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),anchors:z$1.array(z$1.string()).optional(),"applies-to":z$1.array(z$1.string()).optional(),enforcement:z$1.string().optional()}),Oe=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),Te=z$1.object({version:z$1.string().optional(),description:z$1.string().optional(),apiSpec:z$1.string().optional(),context:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),features:z$1.union([z$1.array(Z),z$1.record(B)]).optional(),components:z$1.union([z$1.array(Z),z$1.record(B)]).optional(),gates:z$1.record(Re).optional(),states:z$1.record(Ee).optional(),signals:z$1.record(ke).optional(),aspects:z$1.record(Fe).optional(),relationships:z$1.array(Ae).optional(),flows:z$1.union([z$1.array(Ie),z$1.record(De)]).optional(),references:z$1.array(Oe).optional()});function ze(e){let t=Me(e);return {data:t.data,errors:t.errors}}function Me(e){let t=[],o=[],n;try{n=j.readFileSync(e,"utf8");}catch(c){let f=`Cannot read file: ${c.message}`;return t.push(f),o.push({message:f,type:"file"}),{data:null,errors:t,detailedErrors:o,rawContent:void 0,isYamlValid:false}}let r=n.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),a=null;try{a=z.load(r);}catch(c){let f=c,p=f.mark?.line?f.mark.line+1:void 0,u=`YAML syntax error: ${f.reason||c.message}`;return t.push(`${u}${p?` (line ${p})`:""}`),o.push({message:u,line:p,type:"yaml"}),{data:null,errors:t,detailedErrors:o,rawContent:n,isYamlValid:false}}if(a==null)return {data:{},errors:[],detailedErrors:[],rawContent:n,isYamlValid:true};if(typeof a=="object"&&a!==null){let c=a,f={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let p of Object.keys(c)){let u=p[0],m=f[u];if(!m||p.length<2)continue;let y=p.slice(1),w=c[p];if(typeof w!="object"||w===null)continue;let h=c[m]||{};m in c||(c[m]=h),y in h||(h[y]=w),delete c[p];}}let s=Te.safeParse(a);if(!s.success){for(let c of s.error.issues){let f=c.path.join("."),p=c.message;t.push(`Schema error at ${f||"/"}: ${p}`),o.push({message:p,path:f||"/",type:"schema"});}return {data:a,errors:t,detailedErrors:o,rawContent:n,isYamlValid:true}}return {data:s.data,errors:[],detailedErrors:[],rawContent:n,isYamlValid:true}}function At(e){return z.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function T(e){return e?Array.isArray(e)?e.map(t=>[t.id,t]):Object.entries(e):[]}async function _e(e){let t=P.resolve(e);return (await glob("**/.purpose",{cwd:t,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((n,r)=>{let a=n.split(P.sep).length,s=r.split(P.sep).length;return a-s})}async function te(e){let t=await _e(e),o=[];for(let n of t){let{data:r,errors:a}=ze(n);r&&(o.push({filePath:n,data:r}),a.length>0&&console.warn(`Warnings parsing ${n}:`,a));}return o}function oe(e){let t=new Map;for(let{filePath:o,data:n}of e){let r=T(n.features);for(let[a,s]of r)t.set(a,{item:s,filePath:o});}return t}function se(e){let t=new Map;for(let{filePath:o,data:n}of e){let r=T(n.components);for(let[a,s]of r)t.set(a,{item:s,filePath:o});}return t}function ne(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.gates)for(let[r,a]of Object.entries(n.gates))t.set(r,{item:a,filePath:o});return t}function re(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.states)for(let[r,a]of Object.entries(n.states))t.set(r,{item:a,filePath:o});return t}function ae(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.flows)if(Array.isArray(n.flows))for(let r of n.flows)t.set(r.name,{item:{id:r.name,description:r.description,steps:r.steps},filePath:o});else for(let[r,a]of Object.entries(n.flows))t.set(r,{item:{id:r,description:a.description,gates:a.gates,signals:a.signals,components:a.components,steps:a.steps},filePath:o});return t}function ie(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.signals)for(let[r,a]of Object.entries(n.signals))t.set(r,{item:a,filePath:o});return t}function ce(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.aspects)for(let[r,a]of Object.entries(n.aspects))t.set(r,{item:a,filePath:o});return t}function fe(e){let t=[],o=new Set;for(let{filePath:n,data:r}of e){let a=T(r.features);for(let[c,f]of a)J(`#${c}`,f,n,t,o);let s=T(r.components);for(let[c,f]of s)J(`#${c}`,f,n,t,o);}return t}function J(e,t,o,n,r){if(t.flows)for(let a of t.flows){let s=a.startsWith("$")?a:`$${a}`;r.has(s)||(r.add(s),n.push({symbol:s,type:"flow",sourceSymbol:e,filePath:o}));}if(t.gates)for(let a of t.gates){let s=a.startsWith("^")?a:`^${a}`;r.has(s)||(r.add(s),n.push({symbol:s,type:"gate",sourceSymbol:e,filePath:o}));}if(t.signals)for(let a of t.signals){let s=a.startsWith("!")?a:`!${a}`;r.has(s)||(r.add(s),n.push({symbol:s,type:"signal",sourceSymbol:e,filePath:o}));}if(t.states)for(let a of t.states){let s=a.startsWith("#")?a:a.startsWith("%")?`#${a.slice(1)}`:`#${a}`;r.has(s)||(r.add(s),n.push({symbol:s,type:"component",sourceSymbol:e,filePath:o}));}if(t.components)for(let a of t.components){let s=a.startsWith("#")?a:`#${a}`;r.has(s)||(r.add(s),n.push({symbol:s,type:"component",sourceSymbol:e,filePath:o}));}if(t.aspects)for(let a of t.aspects){let s=a.startsWith("~")?a:`~${a}`;r.has(s)||(r.add(s),n.push({symbol:s,type:"aspect",sourceSymbol:e,filePath:o}));}if(t.description){let a=Ye(t.description);for(let{symbol:s,type:c}of a)r.has(s)||(r.add(s),n.push({symbol:s,type:c,sourceSymbol:e,filePath:o}));}}var Ge=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Ye(e){let t=[],o=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,n;for(;(n=o.exec(e))!==null;){let r=n[1],a=n[2],s,c;switch(r){case "#":c="component",s=`#${a}`;break;case "$":c="flow",s=`$${a}`;break;case "^":c="gate",s=`^${a}`;break;case "!":c="signal",s=`!${a}`;break;case "~":c="aspect",s=`~${a}`;break;case "%":c="component",s=`#${a}`;break;default:continue}Ge.has(s)||t.push({symbol:s,type:c});}return t}function I(e){return e?Array.isArray(e)?e.map(t=>[t.id,t]):Object.entries(e):[]}function W(e){return e?Array.isArray(e)?e.map(t=>t.id):Object.keys(e):[]}function It(e,t){let o=[],n=t?`${t}: `:"",r=I(e.features);for(let[s,c]of r)H(s,c,"feature",n,o);let a=I(e.components);for(let[s,c]of a)H(s,c,"component",n,o);if(e.relationships){let s=new Set([...W(e.features),...W(e.components)]);for(let c of e.relationships){if(typeof c=="string"||!c||!c.from||!c.to)continue;let f=c.from.replace(/^[@#$%~^!?]/,"");!s.has(f)&&!c.from.includes(".")&&o.push({type:"warning",message:`${n}Relationship references unknown source: "${c.from}"`,path:"relationships"});let p=c.to.replace(/^[@#$%~^!?]/,"");!s.has(p)&&!c.to.includes(".")&&o.push({type:"warning",message:`${n}Relationship references unknown target: "${c.to}"`,path:"relationships"});}}if(e.flows){let s=new Set(W(e.components));if(Array.isArray(e.flows)){for(let c of e.flows)if(!(!c||typeof c!="object")&&(c.name||o.push({type:"error",message:`${n}Flow missing required "name" field`,path:"flows"}),c.steps&&Array.isArray(c.steps)))for(let f of c.steps){if(typeof f=="string"||!f||!f.component)continue;let p=f.component.replace(/^#/,"");s.has(p)||o.push({type:"warning",message:`${n}Flow "${c.name}" references unknown component: "${f.component}"`,path:`flows.${c.name}`});}}else for(let[c,f]of Object.entries(e.flows))if(!(!f||typeof f!="object")&&f.steps&&Array.isArray(f.steps))for(let p of f.steps){if(typeof p=="string"||!p||!p.component)continue;let u=p.component.replace(/^#/,"");s.has(u)||o.push({type:"warning",message:`${n}Flow "${c}" references unknown component: "${p.component}"`,path:`flows.${c}`});}}return {valid:o.filter(s=>s.type==="error").length===0,issues:o}}function H(e,t,o,n,r){let a=`${o}s.${e}`;if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(e)||r.push({type:"warning",message:`${n}${o} ID "${e}" should use alphanumeric characters and hyphens`,path:a}),(!t.description||t.description.trim()==="")&&r.push({type:"warning",message:`${n}${o} "${e}" has no description`,path:a}),t.endpoints)for(let s of t.endpoints)/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\//.test(s)||r.push({type:"warning",message:`${n}Endpoint "${s}" in ${o} "${e}" may not be in standard format (e.g., "GET /api/users")`,path:`${a}.endpoints`});}function Dt(e){let t=[],o=new Set;for(let{data:n}of e){let r=I(n.components);for(let[s]of r)o.add(`#${s}`),o.add(s);let a=I(n.features);for(let[s]of a)o.add(`#${s}`),o.add(s);if(n.gates)for(let s of Object.keys(n.gates))o.add(`^${s}`),o.add(s);if(n.signals)for(let s of Object.keys(n.signals))o.add(`!${s}`),o.add(s);if(n.flows)if(Array.isArray(n.flows))for(let s of n.flows)s?.name&&(o.add(`$${s.name}`),o.add(s.name));else for(let s of Object.keys(n.flows))o.add(`$${s}`),o.add(s);if(n.aspects)for(let s of Object.keys(n.aspects))o.add(`~${s}`),o.add(s);if(n.states)for(let s of Object.keys(n.states))o.add(`#${s}`),o.add(s);}for(let{filePath:n,data:r}of e){let a=n?`${n}: `:"",s=[...I(r.components),...I(r.features)];for(let[c,f]of s){if(f.parent){let u=f.parent.replace(/^["']|["']$/g,""),m=u.replace(/^[#$^!~@%?&]/,"");!o.has(u)&&!o.has(m)&&t.push({type:"warning",message:`${a}Component "${c}" references parent "${u}" which is not defined in any .purpose file`,path:`components.${c}.parent`});}let p=[{field:"gates",refs:f.gates},{field:"signals",refs:f.signals},{field:"flows",refs:f.flows},{field:"components",refs:f.components},{field:"aspects",refs:f.aspects}];for(let{field:u,refs:m}of p)if(m)for(let y of m){let w=y.replace(/^[#$^!~@%?&]/,"");!o.has(y)&&!o.has(w)&&t.push({type:"warning",message:`${a}Symbol "${c}" references ${u} "${y}" which is not defined`,path:`components.${c}.${u}`});}}if(r.flows){if(Array.isArray(r.flows)){for(let c of r.flows)if(c?.steps)for(let f of c.steps){if(typeof f=="string"||!f?.component)continue;let p=f.component.replace(/^#/,"");!o.has(f.component)&&!o.has(p)&&t.push({type:"warning",message:`${a}Flow "${c.name}" step references "${f.component}" which is not defined`,path:`flows.${c.name}.steps`});}}else for(let[c,f]of Object.entries(r.flows))if(f?.steps)for(let p of f.steps){if(typeof p=="string"||!p?.component)continue;let u=p.component.replace(/^#/,"");!o.has(p.component)&&!o.has(u)&&t.push({type:"warning",message:`${a}Flow "${c}" step references "${p.component}" which is not defined`,path:`flows.${c}.steps`});}}}return {valid:t.filter(n=>n.type==="error").length===0,issues:t}}var Ne={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function L(e){let t=P.resolve(e),o=P.dirname(t);if(!j.existsSync(t))throw new Error(`Gate config not found: ${t}`);let n=j.readFileSync(t,"utf8"),r=z.load(n);if(!r.version)throw new Error('Gate config missing required "version" field');let a=[],s=r,c=r.gates||s.portals;if(c)for(let[p,u]of Object.entries(c)){let m=p.startsWith("^")?p.slice(1):p;a.push(V(m,u));}if(r.include)for(let p of r.include){let u=P.join(o,p),m=await glob(u.replace(/\\/g,"/"));for(let y of m){let w=await We(y);a.push(...w);}}let f=[];if(r.flows)for(let[p,u]of Object.entries(r.flows))f.push(Ke(p,u));return {version:r.version,gates:a,flows:f,settings:{dev:{...Ne,...r.settings?.dev}}}}async function We(e){let t=j.readFileSync(e,"utf8"),o=z.load(t);if(o.id){let n=o.id,r=n.startsWith("^")?n.slice(1):n;return [V(r,o)]}if(o.gates){let n=[];for(let[r,a]of Object.entries(o.gates)){let s=r.startsWith("^")?r.slice(1):r;n.push(V(s,a));}return n}return []}function V(e,t){let o=[];if(t.locks)for(let r of t.locks)o.push(Be(r));let n=[];if(t.prizes)for(let r of t.prizes)n.push(Ve(r));return {id:e,description:t.description,locks:o,prizes:n,position:t.position}}function Be(e){let t=e,o=[];if(t.keys){for(let n of t.keys)if(typeof n=="string")o.push({expression:n});else if(n.expression){let r=n;o.push({expression:r.expression,description:r.description});}}return {id:t.id,description:t.description,keys:o,mode:t.mode||"all"}}function Ve(e){let t=e;return {id:t.id,oneTime:t.oneTime??false,metadata:t.metadata}}function Ke(e,t){return {id:e,description:t.description,gates:t.gates||[],forkable:t.forkable}}async function le(e){let t=P.resolve(e);return await glob("**/portal.yaml",{cwd:t,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}function Ft(e){if(e instanceof z.YAMLException){let t=(e.reason||"").toLowerCase();return t.includes("duplicated mapping key")||t.includes("duplicate mapping key")?{errorClass:"duplicate-key",detail:"duplicate mapping key"}:["unexpected","expected","bad indentation","mapping values","cannot read a block mapping entry","end of the stream","while scanning","while parsing"].some(n=>t.includes(n))?{errorClass:"syntax",detail:"yaml syntax error"}:{errorClass:"other",detail:"yaml parse error"}}return {errorClass:"other",detail:"yaml parse error"}}var Ue=z$1.object({x:z$1.number(),y:z$1.number()}),qe=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),de=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),we=z$1.object({id:z$1.string(),symbol:z$1.string(),type:z$1.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z$1.string().optional(),position:Ue,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),$e=z$1.object({from:z$1.string(),to:z$1.string(),label:z$1.string().optional(),type:z$1.string().optional()}),Xe=z$1.object({id:z$1.string(),name:z$1.string(),nodes:z$1.array(z$1.string()),color:z$1.string().optional()}),be=z$1.object({viewport:qe,groups:z$1.array(Xe).optional()}),Ze=z$1.object({nodes:z$1.array(we),connections:z$1.array($e),layout:be}),Je=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:Ze});z$1.object({version:z$1.string(),metadata:z$1.object({name:z$1.string(),created:z$1.string(),modified:z$1.string()}),sources:z$1.object({purpose:z$1.array(de).optional(),portal:z$1.array(de).optional()}),nodes:z$1.array(we),connections:z$1.array($e),layout:be,snapshots:z$1.array(Je).optional()});async function He(e,t){let o=[],n=[],r=[],a=[];if(e.sources.purpose)for(let f of e.sources.purpose){let p=P.resolve(t,f.path);try{let u=await te(p);r.push(...u.map(d=>d.filePath));let m=oe(u);for(let[d,{item:g,filePath:b}]of m){let E=["feature",...g.tags||[]];o.push(S({id:`purpose-feature-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:b,data:g,description:g.description,tags:E,componentType:g.type,parentSymbol:g.parent,anchors:g.anchors?.map(xe=>K(xe))}));}let y=se(u);for(let[d,{item:g,filePath:b}]of y)o.push(S({id:`purpose-component-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:b,data:g,description:g.description,tags:g.tags,componentType:g.type,parentSymbol:g.parent,anchors:g.anchors?.map(E=>K(E))}));let w=ne(u);for(let[d,{item:g,filePath:b}]of w)o.push(S({id:`purpose-gate-${d}`,symbol:`^${d}`,type:"gate",source:"purpose",filePath:b,data:g,description:g.description}));let h=re(u);for(let[d,{item:g,filePath:b}]of h)o.push(S({id:`purpose-state-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:b,data:g,description:g.description,tags:["state"]}));let $=ae(u);for(let[d,{item:g,filePath:b}]of $)o.push(S({id:`purpose-flow-${d}`,symbol:`$${d}`,type:"flow",source:"purpose",filePath:b,data:g,description:g.description}));let x=ie(u);for(let[d,{item:g,filePath:b}]of x)o.push(S({id:`purpose-signal-${d}`,symbol:`!${d}`,type:"signal",source:"purpose",filePath:b,data:g,description:g.description}));let R=ce(u);for(let[d,{item:g,filePath:b}]of R)o.push(S({id:`purpose-aspect-${d}`,symbol:`~${d}`,type:"aspect",source:"purpose",filePath:b,data:g,description:g.description,anchors:g.anchors?.map(E=>K(E)),appliesTo:g["applies-to"],tags:g.tags,enforcement:g.enforcement}));let N=fe(u),v=new Set(o.map(d=>d.symbol));for(let d of N)v.has(d.symbol)||(v.add(d.symbol),o.push(S({id:`purpose-ref-${d.type}-${d.symbol.slice(1)}`,symbol:d.symbol,type:d.type,source:"purpose",filePath:d.filePath,data:{referencedFrom:d.sourceSymbol},description:`Referenced from ${d.sourceSymbol}`})));}catch(u){n.push({source:"purpose",filePath:p,message:u.message});}}if(e.sources.portal)for(let f of e.sources.portal){let p=P.resolve(t,f.path);try{let u;if(p.endsWith(".yaml")||p.endsWith(".yml"))u=await L(p),a.push(p);else {let m=await le(p);if(a.push(...m),m.length>0){u=await L(m[0]);for(let y=1;y<m.length;y++){let w=await L(m[y]);u.gates.push(...w.gates),u.flows.push(...w.flows);}}else continue}for(let m of u.gates){o.push(Qe(m,p));for(let y of m.prizes)o.push(S({id:`gate-signal-${m.id}-${y.id}`,symbol:`!${y.id}`,type:"signal",source:"portal",filePath:p,data:y,description:`Signal from gate ${m.id}`}));}for(let m of u.flows)o.push(et(m,p));}catch(u){n.push({source:"portal",filePath:p,message:u.message});}}for(let f of e.nodes){let p=f.tags?.includes("idea");if(!f.content&&!p){let u=o.find(m=>m.symbol===f.symbol);if(u){u.position=f.position,u.tags=f.tags;continue}}o.push(S({id:f.id,symbol:f.symbol,type:f.type,source:"premise",filePath:".premise",data:f,description:f.content,position:f.position,tags:f.tags,created:f.created,modified:f.modified}));}ot(o);let s=new Map;for(let f of o){let p=s.get(f.symbol)||[];p.includes(f.filePath)||p.push(f.filePath),s.set(f.symbol,p);}let c=[];for(let[f,p]of s)p.length>1&&c.push({symbol:f,files:p});return {symbols:o,purposeFiles:r,portalFiles:a,errors:n,timestamp:Date.now(),...c.length>0?{duplicateSymbols:c}:{}}}function S(e){return {...e,data:e.data??null,references:e.references??[],referencedBy:e.referencedBy??[]}}function Qe(e,t){let o=e.id.startsWith("^")?e.id.slice(1):e.id;return S({id:`gate-${o}`,symbol:`^${o}`,type:"gate",source:"portal",filePath:t,data:e,description:e.description,position:e.position})}function et(e,t){return S({id:`gate-flow-${e.id}`,symbol:`$${e.id}`,type:"flow",source:"portal",filePath:t,data:e,description:e.description})}function K(e){let t=e.lastIndexOf(":");if(t===-1||t===e.length-1)return {path:e,lines:0,raw:e};let o=e.slice(t+1),n=e.slice(0,t);if(!/^[\d,\- ]+$/.test(o))return {path:e,lines:0,raw:e};if(o.includes("-")){let[r,a]=o.split("-").map(Number);return {path:n,lines:[r,a],raw:e}}else if(o.includes(",")){let r=o.split(",").map(Number);return {path:n,lines:r,raw:e}}else return {path:n,lines:Number(o),raw:e}}var tt=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function ot(e){let t=new Map(e.map(o=>[o.symbol,o]));for(let o of e){let n=JSON.stringify(o.data),r=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,a=(n.match(r)||[]).filter(s=>!tt.has(s));for(let s of a)if(s!==o.symbol&&t.has(s)){o.references.includes(s)||o.references.push(s);let c=t.get(s);c&&!c.referencedBy.includes(o.symbol)&&c.referencedBy.push(o.symbol);}}}async function st(e){let t={metadata:{name:P.basename(e),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return He(t,e)}function nt(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function rt(e){let t=nt();t.timestamp=e.timestamp;for(let o of e.symbols)t.entries.set(o.id,o),t.byType.has(o.type)||t.byType.set(o.type,[]),t.byType.get(o.type).push(o),t.bySource.has(o.source)||t.bySource.set(o.source,[]),t.bySource.get(o.source).push(o);return t}function C(e,t){for(let o of e.entries.values())if(o.symbol===t)return o}function Se(e,t){return e.byType.get(t)||[]}function _t(e,t){let o=t.toLowerCase(),n=[];for(let r of e.entries.values()){if(r.symbol.toLowerCase().includes(o)){n.push(r);continue}if(r.description?.toLowerCase().includes(o)){n.push(r);continue}if(r.tags?.some(a=>a.toLowerCase().includes(o))){n.push(r);continue}if(r.componentType?.toLowerCase().includes(o)){n.push(r);continue}}return n}function at(e,t){let o=C(e,t);return o?o.referencedBy.map(n=>C(e,n)).filter(n=>n!==void 0):[]}function me(e,t){let o=C(e,t);return o?o.references.map(n=>C(e,n)).filter(n=>n!==void 0):[]}function Gt(e){let t={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[o,n]of e.byType)o in t&&(t[o]=n.length);return t}function it(e){return Array.from(e.entries.values())}function ct(e,t,o){if(P.isAbsolute(e))return {resolvedPath:e,baseUsed:"absolute",exists:j.existsSync(e)};let n=P.join(o,e);if(j.existsSync(n))return {resolvedPath:n,baseUsed:"project-root",exists:true};let r=P.resolve(t,e);return j.existsSync(r)?{resolvedPath:r,baseUsed:"purpose-dir",exists:true}:{resolvedPath:n,baseUsed:"project-root",exists:false}}function Yt(e,t,o){if(P.isAbsolute(e)){let a=j.existsSync(e);return {rootResolves:a,purposeResolves:a,mismatch:false}}let n=j.existsSync(P.join(o,e)),r=j.existsSync(P.resolve(t,e));return {rootResolves:n,purposeResolves:r,mismatch:n!==r}}function ft(e,t){return e.includes("*")?new RegExp("^"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(t):e===t}function Nt(e,t,o){let n=[],r=Se(e,"aspect"),a=new Set;for(let s of r){let c=s.appliesTo||[];if(c.length!==0)for(let f of c)for(let p of t){if(!ft(f,p))continue;let u=s.anchors||[];if(u.length===0){let m=`${s.symbol}::__no-anchors__`;a.has(m)||(a.add(m),n.push({aspectSymbol:s.symbol,anchorRaw:null,kind:"no-anchors"}));}else {let m=s.filePath?P.isAbsolute(s.filePath)?s.filePath:P.resolve(o,s.filePath):o,y=s.filePath?P.dirname(m):o;for(let w of u){let h=`${s.symbol}::${w.raw}`;if(a.has(h))continue;ct(w.path,y,o).exists||(a.add(h),n.push({aspectSymbol:s.symbol,anchorRaw:w.raw,kind:"missing-file"}));}}}}return n}var pt=1,lt=3,U=8,ut=5,ge={"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"},_={component:"component",flow:"flow",gate:"gate",signal:"signal",aspect:"aspect"};async function dt(e){let t=await st(e),o=rt(t),n=it(o).map(s=>s.symbol),r=new Map,a=new Map;for(let s of Se(o,"flow")){let c=s.data,f=c?.sequence||c?.gates||s.references;if(Array.isArray(f))for(let p of f)typeof p!="string"||!p||(r.has(p)||r.set(p,new Set),r.get(p).add(s.symbol),a.has(s.symbol)||a.set(s.symbol,new Set),a.get(s.symbol).add(p));}return {index:o,allSymbols:n,symbolFlows:r,flowMembers:a,generatedAt:new Date().toISOString()}}function mt(e,t){let o=gt(t.radius),n=t.mode??"ego",r=wt(t.symbol,e),a={generatedAt:e.generatedAt,stale:false};if(!r||!C(e.index,r)){let h=St(t.symbol,e.allSymbols);return {root:t.symbol,freshness:a,nodes:[],edges:[],truncated:false,didYouMean:h}}let s=new Set([r]),c=new Set([r]),f=new Map,p=new Map,u=false,m=[r];for(let h=0;h<o;h++){let $=[];for(let x of m){let R=$t(x,e,n),N=R.slice(0,U);if(R.length>U){u=true;let v=R.length-U,d=`${x}::+more`;c.add(d),f.set(`${x}|${d}|uses`,{source:x,target:d,kind:"uses"}),p.set(d,v);}for(let{target:v,kind:d}of N){let g=`${x}|${v}|${d}`;f.has(g)||f.set(g,{source:x,target:v,kind:d}),c.add(v),s.has(v)||(s.add(v),$.push(v));}}if(m=$,m.length===0)break}let y=[];for(let h of c){if(p.has(h)){y.push({id:h,kind:"component",label:`+${p.get(h)} more`});continue}let $=C(e.index,h),x=ve(h,$);y.push({id:h,kind:x,label:yt(h,$),...$?.filePath?{path:$.filePath}:{}});}y.sort((h,$)=>h.id.localeCompare($.id));let w=Array.from(f.values()).sort((h,$)=>h.source!==$.source?h.source.localeCompare($.source):h.target!==$.target?h.target.localeCompare($.target):h.kind.localeCompare($.kind));return {root:r,freshness:a,nodes:y,edges:w,truncated:u}}async function Wt(e,t){let o=await dt(e);return mt(o,t)}function gt(e){let t=typeof e=="number"&&!Number.isNaN(e)?Math.floor(e):pt;return Math.min(Math.max(t,1),lt)}function G(e){return e.replace(/^[#$^!~@%?&]{1,2}/,"")}function ht(e){let t=/^[#$^!~]/.exec(e);return t?t[0]:""}function ve(e,t){if(t?.type&&_[t.type])return _[t.type];let o=ht(e);return o&&ge[o]?ge[o]:"component"}function yt(e,t){return t?.data?.name||G(e)}function wt(e,t){if(!e)return null;if(C(t.index,e))return e;let o=G(e);for(let n of ["#","$","$$","^","!","~"]){let r=`${n}${o}`;if(C(t.index,r))return r}return null}function $t(e,t,o){let n=new Map,r=(s,c)=>{!s||s===e||n.set(`${s}|${c}`,{target:s,kind:c});};if(o==="ego"||o==="ripple"){for(let s of me(t.index,e))r(s.symbol,bt(s));for(let s of at(t.index,e))q(s)==="flow"&&(t.symbolFlows.get(e)?.has(s.symbol)??false)?r(s.symbol,"in-flow"):r(s.symbol,"used-by");}else for(let s of me(t.index,e))q(s)==="flow"&&r(s.symbol,"in-flow");for(let s of t.symbolFlows.get(e)||[])r(s,"in-flow");if(o==="flow")for(let s of t.symbolFlows.get(e)||[])for(let c of t.flowMembers.get(s)||[])r(c,"uses");return Array.from(n.values()).sort((s,c)=>s.target!==c.target?s.target.localeCompare(c.target):s.kind.localeCompare(c.kind))}function q(e){return e.type&&_[e.type]?_[e.type]:ve(e.symbol)}function bt(e){let t=q(e);return t==="gate"?"gated-by":t==="flow"?"in-flow":"uses"}function St(e,t){let o=G(e).toLowerCase(),n=[];for(let r of t){let a=G(r).toLowerCase();if(a===o){n.push({sym:r,dist:0});continue}if(a.includes(o)||o.includes(a)){n.push({sym:r,dist:1});continue}let s=vt(o,a);s<=4&&n.push({sym:r,dist:s});}return n.sort((r,a)=>r.dist!==a.dist?r.dist-a.dist:r.sym.localeCompare(a.sym)),n.slice(0,ut).map(r=>r.sym)}function vt(e,t){let o=e.length,n=t.length;if(o===0)return n;if(n===0)return o;let r=new Array(n+1),a=new Array(n+1);for(let s=0;s<=n;s++)r[s]=s;for(let s=1;s<=o;s++){a[0]=s;for(let c=1;c<=n;c++){let f=e[s-1]===t[c-1]?0:1;a[c]=Math.min(r[c]+1,a[c-1]+1,r[c-1]+f);}[r,a]=[a,r];}return r[n]}var xt=P.join(".paradigm","events"),Pt="classroom-certifications.jsonl";function kt(e){try{return j.existsSync(e)?j.readFileSync(e,"utf8").trim().split(`
3
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function Bt(e){return kt(P.join(e,xt,Pt))}function he(e,t){return e>0?Number((t/e).toFixed(3)):null}function Vt(e){let t=0,o=0,n={};for(let r of e){let a=r.agent;if(!a)continue;let s=r.outcome==="overturned";if(!(s||r.outcome==="survived"))continue;let f=n[a]??{resolved:0,overturned:0,rate:null};f.resolved+=1,s&&(f.overturned+=1),n[a]=f,t+=1,s&&(o+=1);}for(let r of Object.keys(n)){let a=n[r];a.rate=he(a.resolved,a.overturned);}return {overall:he(t,o),perAgent:n}}export{ze as a,Me as b,At as c,_e as d,It as e,Dt as f,L as g,Ft as h,st as i,rt as j,C as k,Se as l,_t as m,at as n,me as o,Gt as p,it as q,ct as r,Yt as s,Nt as t,Wt as u,Bt as v,Vt as w};
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import {e as e$2,f as f$4}from'./chunk-F3OBFUOE.js';import {C,b,l,x,w,v,z as z$1,p as p$1,r,s as s$1,a,t,A,B,q,g as g$1,h as h$1,f as f$3,j as j$2,i,k}from'./chunk-ABHILQLA.js';import {m,j as j$1,k as k$1,l as l$1}from'./chunk-WUSTIEYA.js';import {e}from'./chunk-Q527BPUF.js';import {z,f as f$1,p}from'./chunk-KAFQA7HV.js';import {s,e as e$1,g,b as b$3,f as f$2,h,p as p$2}from'./chunk-GADXREYG.js';import {b as b$1,a as a$2}from'./chunk-EK4ZRIFJ.js';import {f,b as b$2,a as a$1}from'./chunk-ECO3LHCE.js';import*as _ from'fs';import*as j from'path';C();b();b$1();m();s();l();var Ee=new Set(["dismissed","revised"]);function $e(i){let t=(i.reason||"").toLowerCase();return t.includes("override")||t.includes("human-override")?"human-override":"reviewer-reject"}function Fe(i){return i.verdict==="dismissed"?"high":"medium"}function ge(i,t){let e={failuresRecorded:0,entriesRevised:0,certsOverturned:0,scenariosCreated:0},d,r;try{d=b$3(i).filter(n=>n.type==="user-verdict"&&n.verdict&&Ee.has(n.verdict)),r=p$2(i);}catch(n){return a$2.component("#field-failure-reducer").warn("failed to read session inputs",{error:n instanceof Error?n.message:String(n)}),e}if(d.length===0||r.length===0)return e;let m=new Map;for(let n of r){if(!n.orchestrationId)continue;let s=m.get(n.orchestrationId)??[];s.push(n),m.set(n.orchestrationId,s);}let u=new Set;for(let n of g$1(i))for(let s of n.attributedEntryIds)u.add(`${s}::${n.orchestrationId}`);for(let n of d){let s=n.orchestrationId;if(!s)continue;let f=m.get(s);if(!f||f.length===0)continue;let b=$e(n),l=Fe(n),a=n.symbols??[],c=n.reason||n.revisionDelta||`${n.verdict} verdict`;for(let p of f){let y=p.agentId;for(let v of p.notebookEntryIds){let S=`${v}::${s}`;if(u.has(S))continue;u.add(S);let R=h$1(s,v),o={ts:new Date().toISOString(),orchestrationId:s,agent:y,signal:b,severity:l,attributedEntryIds:[v],symbols:a,detail:c,sourceEvent:`verdict:${n.verdict}`};f$3(i,o),e.failuresRecorded++,j$1(y,v,{failureId:R,signal:b,detail:c,severity:l},i)&&e.entriesRevised++,j$2(i,v,R)&&e.certsOverturned++;let D=e$2(R);f$4(i,{id:D,scenario:c,probes:[{agent:y,learning_ref:v,claim:c}],origin:"field-failure",origin_ref:R,expected:{must:"survive"}})&&e.scenariosCreated++;}}}return e.failuresRecorded>0&&a$2.flow("$classroom-fail-loop").info("field-failure reducer pass complete",{failuresRecorded:e.failuresRecorded,entriesRevised:e.entriesRevised,certsOverturned:e.certsOverturned,scenariosCreated:e.scenariosCreated}),e}b$1();l();m();var ke=14,Ae=30,Pe=2,Oe=.05,xe=1440*60*1e3;function ye(i,t){if(!i)return null;let e=Date.parse(i);return Number.isNaN(e)?null:(t-e)/xe}function he(i$1,t={}){let e={certsSurvived:0,entriesDecayed:0},d=t.now??Date.now(),r=t.survivalWindowDays??ke,m=t.idleWindowDays??Ae,u=t.lowAppliedThreshold??Pe,n=t.decayDecrement??Oe;try{let s=i(i$1),f=g$1(i$1),b=new Set;for(let a of f)for(let c of a.attributedEntryIds??[])b.add(c);let l=new Set;for(let a of s){if(a.outcome!=="pending"||l.has(a.entryId)||b.has(a.entryId))continue;let c=ye(typeof a.ts=="string"?a.ts:void 0,d);c===null||c<r||k(i$1,a.entryId)&&(l.add(a.entryId),e.certsSurvived++);}}catch(s){a$2.component("#classroom-decay").warn("survived-flip pass failed",{error:s instanceof Error?s.message:String(s)});}try{for(let s of k$1(i$1)){let{entry:f}=s;if((f.appliedCount??0)>u)continue;let l=ye(f.lastAppliedAt,d);l===null||l<m||l$1(s,n)&&e.entriesDecayed++;}}catch(s){a$2.component("#classroom-decay").warn("unused-decay pass failed",{error:s instanceof Error?s.message:String(s)});}return (e.certsSurvived>0||e.entriesDecayed>0)&&a$2.flow("$classroom-fail-loop").info("decay pass complete",{certsSurvived:e.certsSurvived,entriesDecayed:e.entriesDecayed}),e}z();f();s();function ot(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Ne(i){let t=Date.now(),e=i.match(/^(\d+)(m|h|d)$/);if(e){let d=parseInt(e[1],10),r=e[2],m=r==="m"?d*6e4:r==="h"?d*36e5:d*864e5;return new Date(t-m).toISOString()}return i}async function st(i,t$1,e$1){let d=r=>JSON.stringify(r,null,2);switch(i){case "paradigm_ambient_nominations":{t(e$1.rootDir);let m=t$1.pending_only!==false,u=t$1.limit||20,n=p$1(e$1.rootDir,{agent:t$1.agent,urgency:t$1.urgency,pending_only:m,limit:u+20}),s=A(e$1.rootDir);n=B(n,s).slice(0,u);let f=j.join(e$1.rootDir,".paradigm/events/nominations.jsonl");if(_.existsSync(f))try{let l=_.readFileSync(f,"utf8"),a=new Set(n.map(p=>p.id)),c=l.trim().split(`
3
+ `).map(p=>{try{let y=JSON.parse(p);return a.has(y.id)?(y.surfaced=!0,JSON.stringify(y)):p}catch{return p}});_.writeFileSync(f,c.join(`
4
+ `)+`
5
+ `,"utf8");}catch{}let b={count:n.length,nominations:n.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t$1.include_debates){let a=q(e$1.rootDir).filter(c=>!c.resolution);b.debates=a.map(c=>({id:c.id,topic:c.topic,type:c.type,nominations:c.nominations})),b.debate_count=a.length;}return {text:d(b),handled:true}}case "paradigm_ambient_events":{let r=t$1.since?Ne(t$1.since):void 0,m=t$1.limit||50,u=a(e$1.rootDir,{type:t$1.type,source:t$1.source,symbol:t$1.symbol,agent:t$1.agent,since:r,limit:m});return {text:d({count:u.length,events:u.map(n=>({id:n.id,type:n.type,source:n.source,timestamp:n.timestamp,path:n.path,symbols:n.symbols,context:n.context,agent:n.agent,tool:n.tool,severity:n.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r$1=t$1.nomination_id,m=t$1.response,u=t$1.reason,n=r(e$1.rootDir,r$1,m,u);if(n)try{let{appendSessionWorkEntry:f,appendVerdictEntry:b}=await import('./session-work-log-KZX4PGUL.js'),a=p$1(e$1.rootDir,{limit:500}).find(p=>p.id===r$1),c={timestamp:new Date().toISOString(),type:"user-verdict",agent:a?.agent,nominationId:r$1,verdict:m,reason:u};f(e$1.rootDir,c),b(e$1.rootDir,c);}catch{}let s=false;return t$1.resolve_debate&&n&&(s=s$1(e$1.rootDir,t$1.resolve_debate,r$1,t$1.reason)),{text:d({engaged:n,nomination_id:r$1,response:m,debate_resolved:s||void 0}),handled:true}}case "paradigm_context_compose":{let r=t$1.agent,m=t$1.symbols||[],u=t$1.include_nominations!==false,n=t$1.include_decisions!==false,s=t$1.include_journal!==false,f=t$1.max_decisions||5,b=t$1.max_journal||5,l=f$1(e$1.rootDir,r);if(!l)return {text:d({error:`Agent profile not found: ${r}`}),handled:true};let a=[],c=p(l,m);if(c.trim()&&a.push(c),n){let p=e(e$1.rootDir,{status:"active",limit:f});if(p.length>0){a.push("## Recent Team Decisions");for(let y of p)a.push(`- **${y.title}**: ${y.decision.slice(0,150)}${y.decision.length>150?"...":""}`);a.push("");}}if(s){let p=b$2(r,{transferable:true,limit:b});if(p.length>0){a.push("## Transferable Insights");for(let y of p)a.push(`- [${y.trigger}] ${y.insight.slice(0,150)}${y.insight.length>150?"...":""}`);a.push("");}}if(u){let p=p$1(e$1.rootDir,{pending_only:true,limit:10});if(p.length>0){a.push("## Pending Nominations");for(let y of p)a.push(`- [${y.urgency}] ${y.brief}`);a.push("");}}return {text:d({agent:r,context:a.join(`
6
+ `),sections_included:{profile:true,decisions:n,journal:s,nominations:u}}),handled:true}}case "paradigm_ambient_promote":{let r=t$1.agent,m=z$1(e$1.rootDir,r);return {text:d({agent:r,promoted:m.promoted,entries:m.entries}),handled:true}}case "paradigm_ambient_learn":{let r=t$1.agent,m=t$1.dry_run===true,u=w(e$1.rootDir,r);if(m)return {text:d({agent:r,dry_run:true,stats:u,note:u.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(u.acceptRate*100).toFixed(0)}% \u2014 ${u.acceptRate>.8?"would lower threshold":u.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let n=v(e$1.rootDir,r);return {text:d({agent:r,...n,stats:u}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let r=x(e$1.rootDir);return {text:d(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:d(await He(e$1.rootDir,t$1)),handled:true};default:return {text:`Unknown ambient tool: ${i}`,handled:false}}}var Ce={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function We(i){try{let t=j.join(i,".paradigm","config.yaml");if(_.existsSync(t)){let d=_.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(d)return d[1].trim()}}catch{}return j.basename(i)}async function He(i,t={}){let e=t.dry_run===true,d=We(i),r=e$1(i).filter(o=>o.verdict&&o.agent),m=g(i).filter(o=>o.agent&&o.corrections.length>0),u=b$3(i),n=e?{failuresRecorded:0,entriesRevised:0,certsOverturned:0}:ge(i),s=e?{certsSurvived:0,entriesDecayed:0}:he(i);if(r.length===0&&m.length===0)return {sessionEntries:u.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:e,details:[],fieldFailures:n,decay:s};let f=new Map;for(let o of r){let g=o.agent;f.has(g)||f.set(g,[]),f.get(g).push(o);}let b=u.filter(o=>o.type==="agent-contribution"),l=new Map;for(let o of b)o.agent&&(l.has(o.agent)||l.set(o.agent,[]),l.get(o.agent).push(o));let a=[],c={},p=0;for(let[o,g]of f){c[o]=0;let I=g.filter(h=>h.verdict==="accepted").length;g.filter(h=>h.verdict==="dismissed").length;g.filter(h=>h.verdict==="revised").length;let k=g.length,be=k>0?I/k:0;for(let h of g){let A=Ce[h.verdict];if(!A)continue;let ve=l.get(o)?.shift(),N=Te(h,ve,{acceptRate:be,total:k,accepted:I}),_e=typeof h.confidence=="number"?h.confidence:h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,Re={agent:o,verdict:h.verdict,trigger:A,insight:N,symbols:h.symbols};if(a.push(Re),e)c[o]++,p++;else try{a$1(o,{trigger:A,insight:N,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:_e,project:d,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(we=>`symbol:${we}`)]}),c[o]++,p++;}catch{}}}let y=new Set;for(let o of m){let g=o.agent;y.add(g),c[g]===void 0&&(c[g]=0);let I=`Self-revision during iteration round ${o.round}: ${o.corrections.join("; ")}`;if(a.push({agent:g,verdict:"iteration-revision",trigger:"self_reflection",insight:I,symbols:o.symbols}),e)c[g]++,p++;else try{a$1(g,{trigger:"self_reflection",insight:I,confidence_before:.6,confidence_after:typeof o.confidence=="number"?o.confidence:.75,project:d,transferable:!1,tags:["postflight","iteration-revision",`round:${o.round}`,...(o.symbols||[]).map(D=>`symbol:${D}`)]}),c[g]++,p++;}catch{}}let v={},S=0,R=new Set([...f.keys(),...y]);if(!e)for(let o of R)try{let g=z$1(i,o);g.promoted>0&&(v[o]=g.promoted,S+=g.promoted);}catch{}return !e&&r.length>0&&f$2(i,r.map(o=>o.nominationId).filter(Boolean)),!e&&m.length>0&&h(i,m.map(o=>o.id)),{sessionEntries:u.length,agentsProcessed:Array.from(R),journalsWritten:p,journalsByAgent:c,promoted:S,promotedByAgent:v,dryRun:e,details:a,fieldFailures:n,decay:s}}function Te(i,t,e){let d=i.symbols?.length?` (symbols: ${i.symbols.join(", ")})`:"",r=i.reason?` Reason: ${i.reason}.`:"";switch(i.verdict){case "accepted":return `Contribution accepted by user${d}.${r}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "dismissed":return `Contribution dismissed by user${d}.${r}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "revised":return `Contribution revised by user${d}.${r}`+(i.revisionDelta?` Delta: "${i.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;default:return `Unknown verdict "${i.verdict}"${d}.${r}`}}export{ot as a,st as b,He as c};
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import {a,O,l as l$1,D,G,L,F,K,J,I as I$1,N}from'./chunk-3F4QP2Z5.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {a as a$4}from'./chunk-VOPJ47QY.js';import {b as b$2}from'./chunk-RGSFU2YW.js';import {m,q as q$1,k,n,o,l,i,j as j$1,g}from'./chunk-TMDPDIWA.js';import {f}from'./chunk-KLBH26PA.js';import {j,a as a$3,i as i$1,b as b$1,h as h$1,g as g$2,c,d as d$2}from'./chunk-GRZQIKST.js';import {d,g as g$1,e,h,j as j$2,f as f$1}from'./chunk-ACJWUOMA.js';import {b,a as a$1}from'./chunk-EK4ZRIFJ.js';import*as I from'fs';import*as E from'path';import*as q from'js-yaml';import {execSync}from'child_process';import*as Et from'os';b();b();var Ht=".paradigm/navigator.yaml";async function st(n){let e=E.join(n,Ht);if(!I.existsSync(e))return {config:null,configPath:null};try{let o=I.readFileSync(e,"utf8");return {config:q.load(o),configPath:e}}catch(o){return a$1.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function rt(n,e,o){switch(e.intent){case "find":return Mt(n,e.target||"");case "explore":return Bt(n,e.target||"");case "context":return Jt(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Mt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let r=n.symbols[e];if(r)t.paths.push(r),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${r}`;else {let s=Object.entries(n.symbols).filter(([i])=>i.includes(e.slice(1))).slice(0,5);s.length>0?(t.paths=s.map(([,i])=>i),t.symbols=s.map(([i])=>i),t.explanation=`Found ${s.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let r=Object.entries(n.symbols).filter(([s])=>s.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(r.length>0)t.paths=r.map(([,s])=>s),t.symbols=r.map(([s])=>s),t.explanation=`Found ${r.length} symbols matching "${e}"`;else {let s=Gt(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=we(t.paths,n),t}function Bt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Jt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=qt(r);for(let[i,a]of Object.entries(n.structure))a&&s.some(c=>i.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[i,a]of Object.entries(n.symbols)){let c=i.slice(1).toLowerCase();s.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(i));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],r.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!r.includes("doc")&&!r.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Gt(n,e){let o=e.toLowerCase();for(let[t,r]of Object.entries(n.structure))if(r&&(t.toLowerCase().includes(o)||o.includes(t.toLowerCase())))return r;return null}function qt(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o.length>2&&!e.has(o))}function we(n,e){let o={};for(let t of n){let r=0;e.key_files.config.some(s=>t.includes(s))&&(r+=100),e.key_files.entry.some(s=>t.includes(s))&&(r+=80),e.key_files.types.some(s=>t.includes(s))&&(r+=60),r-=t.split("/").length*2,o[t]=r;}return [...n].sort((t,r)=>(o[r]||0)-(o[t]||0))}b();function Ut(n){let e=E.resolve(n),o=I.readFileSync(e,"utf8"),t=q.load(o);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let r={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let s of t.members)if(typeof s=="object"&&s!==null){let i=s;r.members.push({name:String(i.name||""),path:String(i.path||""),role:i.role,exports:Array.isArray(i.exports)?i.exports.map(String):void 0});}}return r}function at(n,e){let o=E.resolve(n),t=E.resolve(o,e);if(!I.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=Ut(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=E.dirname(t),i="";for(let c of r.members){let l=E.resolve(s,c.path);if(it(l)===it(o)){i=c.name;break}}if(!i)return a$1.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:r.name}),null;let a=new Map;for(let c of r.members){if(c.name===i)continue;let l=E.resolve(s,c.path),p=E.join(l,".paradigm","scan-index.json");if(!I.existsSync(p)){a$1.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:p});continue}try{let f=JSON.parse(I.readFileSync(p,"utf8")),k=Kt(f);c.exports&&c.exports.length>0&&(k=zt(k,c.exports));let w=null,x=E.join(l,"portal.yaml");if(I.existsSync(x))try{let y=I.readFileSync(x,"utf8"),j=q.load(y);j&&(w=j);}catch{}a.set(c.name,{index:k,gateConfig:w});}catch(f){a$1.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:f.message});}}return {config:r,workspacePath:t,currentMember:i,siblingIndices:a}}function zt(n,e){let t=q$1(n).filter(r=>{let s=r.symbol;return e.some(i=>Vt(i,s))});return Qt(t)}function Vt(n,e){let o=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${o}$`,"i").test(e)}function xe(n,e){let o=[];for(let[t,r]of n.siblingIndices){let s=m(r.index,e);for(let i of s)o.push({project:t,symbol:`${t}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function ct(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=q$1(s.index);for(let c of a){let l=c.references||[],p=c.description||"",f=l.some(w=>w===t||w===e||w.endsWith(`/${t}`)),k=p.includes(t);(f||k)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}function it(n){return E.resolve(n).replace(/\/+$/,"")}function Kt(n){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},o=[];for(let[t,r]of Object.entries(e)){let s=n[t];if(!(!s||typeof s!="object"))for(let[i,a]of Object.entries(s)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[r]||"#";o.push({id:i,symbol:a.symbol||`${c}${i}`,type:r,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return j$1({symbols:o,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function Qt(n){return j$1({symbols:n.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}var Yt={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function to(){return [Yt]}async function pt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await st(o.rootDir);if(r.config||(r={config:Xt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await a.getOrCompute(s,()=>{let c=rt(r.config,t,o.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let p=xe(o.workspace,t.target);p.length>0&&(l.workspaceResults=p.slice(0,5).map(f=>({symbol:f.symbol,type:f.type,description:f.description,project:f.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let p=xe(o.workspace,t.task);p.length>0&&(l.workspaceContext=p.slice(0,5).map(f=>({symbol:f.symbol,type:f.type,description:f.description,project:f.project})));}}return JSON.stringify(l,null,2)}),a$1=i;if(e.response_format==="concise")try{let c=JSON.parse(i);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a$1=JSON.stringify(c,null,2);}catch{}try{let c=E.join(o.rootDir,".paradigm",".nav-called");I.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Xt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=q$1(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function mt(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of i)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
2
+ import {a,O,l as l$1,D,G,L,F,K,J,I as I$1,N}from'./chunk-VHVUJGZ2.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {a as a$4}from'./chunk-VOPJ47QY.js';import {b as b$2}from'./chunk-5LIE2QMS.js';import {m,q as q$1,k,n,o,l,i,j as j$1,g}from'./chunk-SGLIPRIC.js';import {f}from'./chunk-KLBH26PA.js';import {j,a as a$3,i as i$1,b as b$1,h as h$1,g as g$2,c,d as d$2}from'./chunk-GRZQIKST.js';import {d,g as g$1,e,h,j as j$2,f as f$1}from'./chunk-74NGU6YN.js';import {b,a as a$1}from'./chunk-EK4ZRIFJ.js';import*as I from'fs';import*as E from'path';import*as q from'js-yaml';import {execSync}from'child_process';import*as Et from'os';b();b();var Ht=".paradigm/navigator.yaml";async function st(n){let e=E.join(n,Ht);if(!I.existsSync(e))return {config:null,configPath:null};try{let o=I.readFileSync(e,"utf8");return {config:q.load(o),configPath:e}}catch(o){return a$1.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function rt(n,e,o){switch(e.intent){case "find":return Mt(n,e.target||"");case "explore":return Bt(n,e.target||"");case "context":return Jt(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Mt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let r=n.symbols[e];if(r)t.paths.push(r),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${r}`;else {let s=Object.entries(n.symbols).filter(([i])=>i.includes(e.slice(1))).slice(0,5);s.length>0?(t.paths=s.map(([,i])=>i),t.symbols=s.map(([i])=>i),t.explanation=`Found ${s.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let r=Object.entries(n.symbols).filter(([s])=>s.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(r.length>0)t.paths=r.map(([,s])=>s),t.symbols=r.map(([s])=>s),t.explanation=`Found ${r.length} symbols matching "${e}"`;else {let s=Gt(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=we(t.paths,n),t}function Bt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Jt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=qt(r);for(let[i,a]of Object.entries(n.structure))a&&s.some(c=>i.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[i,a]of Object.entries(n.symbols)){let c=i.slice(1).toLowerCase();s.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(i));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],r.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!r.includes("doc")&&!r.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=we(t.paths,n),t}function Gt(n,e){let o=e.toLowerCase();for(let[t,r]of Object.entries(n.structure))if(r&&(t.toLowerCase().includes(o)||o.includes(t.toLowerCase())))return r;return null}function qt(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o.length>2&&!e.has(o))}function we(n,e){let o={};for(let t of n){let r=0;e.key_files.config.some(s=>t.includes(s))&&(r+=100),e.key_files.entry.some(s=>t.includes(s))&&(r+=80),e.key_files.types.some(s=>t.includes(s))&&(r+=60),r-=t.split("/").length*2,o[t]=r;}return [...n].sort((t,r)=>(o[r]||0)-(o[t]||0))}b();function Ut(n){let e=E.resolve(n),o=I.readFileSync(e,"utf8"),t=q.load(o);if(!t||typeof t!="object")throw new Error(`Invalid workspace file: ${n}`);let r={version:String(t.version||"1.0"),name:String(t.name||"unnamed-workspace"),members:[]};if(Array.isArray(t.members)){for(let s of t.members)if(typeof s=="object"&&s!==null){let i=s;r.members.push({name:String(i.name||""),path:String(i.path||""),role:i.role,exports:Array.isArray(i.exports)?i.exports.map(String):void 0});}}return r}function at(n,e){let o=E.resolve(n),t=E.resolve(o,e);if(!I.existsSync(t))return a$1.component("#workspace-loader").warn("Workspace file not found",{workspacePath:t}),null;let r;try{r=Ut(t);}catch(c){return a$1.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let s=E.dirname(t),i="";for(let c of r.members){let l=E.resolve(s,c.path);if(it(l)===it(o)){i=c.name;break}}if(!i)return a$1.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:r.name}),null;let a=new Map;for(let c of r.members){if(c.name===i)continue;let l=E.resolve(s,c.path),p=E.join(l,".paradigm","scan-index.json");if(!I.existsSync(p)){a$1.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:p});continue}try{let f=JSON.parse(I.readFileSync(p,"utf8")),k=Kt(f);c.exports&&c.exports.length>0&&(k=zt(k,c.exports));let w=null,x=E.join(l,"portal.yaml");if(I.existsSync(x))try{let y=I.readFileSync(x,"utf8"),j=q.load(y);j&&(w=j);}catch{}a.set(c.name,{index:k,gateConfig:w});}catch(f){a$1.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:f.message});}}return {config:r,workspacePath:t,currentMember:i,siblingIndices:a}}function zt(n,e){let t=q$1(n).filter(r=>{let s=r.symbol;return e.some(i=>Vt(i,s))});return Qt(t)}function Vt(n,e){let o=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${o}$`,"i").test(e)}function xe(n,e){let o=[];for(let[t,r]of n.siblingIndices){let s=m(r.index,e);for(let i of s)o.push({project:t,symbol:`${t}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function ct(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=q$1(s.index);for(let c of a){let l=c.references||[],p=c.description||"",f=l.some(w=>w===t||w===e||w.endsWith(`/${t}`)),k=p.includes(t);(f||k)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}function it(n){return E.resolve(n).replace(/\/+$/,"")}function Kt(n){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},o=[];for(let[t,r]of Object.entries(e)){let s=n[t];if(!(!s||typeof s!="object"))for(let[i,a]of Object.entries(s)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[r]||"#";o.push({id:i,symbol:a.symbol||`${c}${i}`,type:r,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return j$1({symbols:o,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function Qt(n){return j$1({symbols:n.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}var Yt={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function to(){return [Yt]}async function pt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await st(o.rootDir);if(r.config||(r={config:Xt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await a.getOrCompute(s,()=>{let c=rt(r.config,t,o.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let p=xe(o.workspace,t.target);p.length>0&&(l.workspaceResults=p.slice(0,5).map(f=>({symbol:f.symbol,type:f.type,description:f.description,project:f.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let p=xe(o.workspace,t.task);p.length>0&&(l.workspaceContext=p.slice(0,5).map(f=>({symbol:f.symbol,type:f.type,description:f.description,project:f.project})));}}return JSON.stringify(l,null,2)}),a$1=i;if(e.response_format==="concise")try{let c=JSON.parse(i);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a$1=JSON.stringify(c,null,2);}catch{}try{let c=E.join(o.rootDir,".paradigm",".nav-called");I.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a$1}}function Xt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=q$1(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function mt(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of i)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
3
3
  `);for(let l of c.slice(0,t)){let p=l.match(/^(.+?):(\d+):(.*)$/);if(p){let[,f,k,w]=p,x=E.relative(n,f),y="unknown";x.includes(".purpose")||x.includes("portal.yaml")?y="purpose":w.includes("//")||w.includes("#")||w.includes("*")?y="comment":y="code",r.push({filePath:x,line:parseInt(k,10),content:w.trim().slice(0,200),context:y});}}return r}b();var en=30*1e3,ut=new Map;async function gt(n){let e=E.resolve(n),o=ut.get(e);if(o&&Date.now()-o.loadedAt<en)return o.index;let t=await tn(e);return t&&ut.set(e,{index:t,loadedAt:Date.now()}),t}async function tn(n){let e=E.join(n,".paradigm","flow-index.json");if(!I.existsSync(e))return null;try{let o=I.readFileSync(e,"utf8");return JSON.parse(o)}catch(o){return a$1.component("#flow-loader").error("Error parsing flow-index.json",{error:o}),null}}function nn(n,e){let o=n.symbolToFlows[e]||[],t=[];for(let r of o){let s=n.flows[r];if(!s)continue;let i=s.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of i){let l=s.steps.slice(c+1).map(p=>p.id);t.push({flowId:s.id,definedIn:s.definedIn,description:s.description,trigger:s.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:s.validation});}}return t}function yt(n,e){let o=nn(n,e),t=new Set;for(let i of o)i.validation?.command&&t.add(i.validation.command);let r="low",s=o.reduce((i,a)=>i+a.downstreamSteps.length,0);return o.length>3||s>10?r="high":(o.length>1||s>3)&&(r="medium"),{symbol:e,totalFlows:o.length,impactLevel:r,affectedFlows:o,validationCommands:Array.from(t),suggestion:o.length>0?`Changes to ${e} may affect ${o.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function go(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function le(n$1,e,o$1){if(n$1!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:r=3,includeWorkspace:s=false,response_format:i}=e,a=k(o$1.index,t);if(!a){let u=on(o$1.rootDir,t);return O(u.length,n$1),{handled:true,text:u}}let c=Math.min(Math.max(r||3,1),5),l$2=n(o$1.index,t),p=new Set([t]),f=new Map;function k$1(u,P){if(P>=c)return;let v=[];for(let b of u){if(p.has(b))continue;p.add(b);let D=n(o$1.index,b);for(let T of D)p.has(T.symbol)||v.push(T.symbol);}v.length>0&&(f.set(P+1,v),k$1(v,P+1));}k$1(l$2.map(u=>u.symbol),1);let w=new Set;for(let[,u]of f)for(let P of u)P!==t&&!l$2.find(v=>v.symbol===P)&&w.add(P);let x=o(o$1.index,t),y=l$2.length+w.size,j="low";y>10?j="high":y>3&&(j="medium");let N=await gt(o$1.rootDir),F=null;if(N){let u=yt(N,t);u.totalFlows>0&&(u.impactLevel==="high"&&j==="low"?j="medium":u.impactLevel==="high"&&(j="high"),F={totalFlows:u.totalFlows,affectedFlows:u.affectedFlows.map(P=>({flowId:P.flowId,impactLevel:P.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${P.stepAffected.position}, affects ${P.downstreamSteps.length} downstream steps`})),validationSuggestion:u.validationCommands.length>0?`Run: ${u.validationCommands[0]}`:void 0});}let $=new Set([t,...l$2.map(u=>u.symbol),...w]),A=[];try{let u=l(o$1.index,"gate");for(let P of u)$.has(P.symbol)&&A.push({gate:P.symbol,description:P.description});for(let P of l$2)P.type==="gate"&&!A.find(v=>v.gate===P.symbol)&&A.push({gate:P.symbol,description:P.description});}catch{}let d={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:j,analysis:{directlyAffected:l$2.map(u=>({symbol:u.symbol,type:u.type,description:u.description})),indirectlyAffected:Array.from(w),indirectByLevel:Object.fromEntries(f),dependsOn:x.map(u=>({symbol:u.symbol,type:u.type}))},summary:{directCount:l$2.length,indirectCount:w.size,totalAffected:y,dependsOnCount:x.length,levelsAnalyzed:c},recommendation:sn(j)};F&&(d.affectedFlows=F),A.length>0&&(d.affectedGates=A),d.suggestedReviewScope=rn(j,l$2.length,w.size,A.length,F?.totalFlows??0);try{let u=await l$1(o$1.rootDir,t);u.length>0&&(d.personas_affected=u,u.length>2&&j==="low"&&(d.impact="medium"));}catch{}try{let u=D(o$1.rootDir,t);u.length>0&&(d.university_content_affected=u.map(P=>({id:P.id,title:P.title,type:P.type,stale:P.stale})));}catch{}if(s&&o$1.workspace){let u=ct(o$1.workspace,t);if(u.length>0){d.workspaceImpact={siblings:u.map(v=>({project:v.project,references:v.references.map(b=>({symbol:b.symbol,type:b.type,description:b.description}))}))};let P=u.reduce((v,b)=>v+b.references.length,0);P>0&&j==="low"&&(d.impact="medium"),P>5&&(d.impact="high");}}let _=i==="concise"?{symbol:d.symbol,impact:d.impact,summary:d.summary}:d,O$1=JSON.stringify(_,null,2);return O(O$1.length,n$1),{handled:true,text:O$1}}function on(n,e){let o=mt(n,e,{maxResults:20});if(o.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(o.map(i=>i.filePath))],r={};for(let i of o)r[i.context]=(r[i.context]||0)+1;let s="low";return t.length>10||o.length>20?s="high":(t.length>3||o.length>5)&&(s="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:s,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:o.length,contextBreakdown:r,sampleReferences:o.slice(0,5).map(i=>({file:i.filePath,line:i.line,preview:i.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function sn(n){switch(n){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function rn(n,e,o,t,r){let s=[];return e>0&&s.push(`Review ${e} direct dependent(s) for breaking changes`),o>0&&s.push(`Scan ${o} indirect dependent(s) for cascading effects`),t>0&&s.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),r>0&&s.push(`Validate ${r} affected flow(s) end-to-end`),n==="high"?s.push("Consider running full test suite before merging"):n==="medium"&&s.push("Run targeted tests for affected components"),s.length===0&&s.push("No downstream dependents detected - safe to proceed"),s}b();b();var an=30*1e3,ve=new Map,bt=".paradigm/wisdom";async function wt(n){let e=E.resolve(n),o=ve.get(e);if(o&&Date.now()-o.loadedAt<an)return o.context;let t=await cn(e);return ve.set(e,{context:t,loadedAt:Date.now()}),t}async function cn(n){let e$1=E.join(n,bt),o=I.existsSync(e$1),[t,r,s,i]=o?await Promise.all([ln(e$1),dn(e$1),pn(e$1),fn(e$1)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e(),l=f$1();}catch{}let p=new Set(r.map(y=>y.id)),f=r.map(y=>({...y,scope:"project"}));for(let y of a)p.has(y.id)||f.push({...y,scope:"global"});let k=new Set(i.map(y=>y.id)),w=i.map(y=>({...y,scope:"project"}));for(let y of c)k.has(y.id)||w.push({...y,scope:"global"});let x=t;if(l&&!t)x=l;else if(l&&t){let y={...t.by_symbol};if(l.by_symbol)for(let[j,N]of Object.entries(l.by_symbol))y[j]||(y[j]=N);x={...t,by_symbol:y,global:{...l.global,...t.global}};}return {preferences:x,antipatterns:f,decisions:w,expertise:s}}function V(n){let e=E.resolve(n);ve.delete(e);}async function ln(n){let e=E.join(n,"preferences.yaml");if(!I.existsSync(e))return null;try{let o=I.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:o}),null}}async function dn(n){let e=E.join(n,"antipatterns.yaml");if(!I.existsSync(e))return [];try{let o=I.readFileSync(e,"utf8");return q.load(o).antipatterns||[]}catch(o){return a$1.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:o}),[]}}async function pn(n){let e=E.join(n,"expertise.yaml");if(!I.existsSync(e))return null;try{let o=I.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:o}),null}}var ht=new Set;async function fn(n){let e=E.join(n,"decisions");if(!I.existsSync(e))return [];let o=[];try{let t=I.readdirSync(e);t.some(s=>s.endsWith(".yaml")||s.endsWith(".yml"))&&!ht.has(e)&&(ht.add(e),a$1.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let s of t){if(!s.endsWith(".yaml")&&!s.endsWith(".yml"))continue;let i=E.join(e,s);try{let a=I.readFileSync(i,"utf8"),c=q.load(a);o.push(c);}catch(a){a$1.component("#wisdom-loader").error(`Error parsing ${s}`,{error:a});}}}catch(t){a$1.component("#wisdom-loader").error("Error reading decisions directory",{error:t});}return o.sort((t,r)=>t.id.localeCompare(r.id)),o}function St(n,e){return e.map(o=>mn(n,o))}function mn(n,e){let o=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(i=>i.symbols.some(a=>a===e||de(e,a))),r=n.decisions.filter(i=>i.symbols.some(a=>a===e||de(e,a))),s=n.expertise?.experts.filter(i=>i.symbols?.some(a=>a===e||de(e,a)))||[];return {symbol:e,preferences:o,antipatterns:t,decisions:r,experts:s}}function xt(n,e){return n.expertise?n.expertise.experts.filter(o=>!!(e.symbol&&o.symbols&&o.symbols.some(t=>t===e.symbol||de(e.symbol,t))||e.area&&o.areas&&o.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function de(n,e){if(e.endsWith("*")){let o=e.slice(0,-1);return n.startsWith(o)}return n===e}async function vt(n,e){let o=E.join(n,bt),t=E.join(o,"antipatterns.yaml");I.existsSync(o)||I.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(I.existsSync(t))try{let s=I.readFileSync(t,"utf8"),i=q.load(s);i&&typeof i=="object"&&(r={version:i.version||"1.0",antipatterns:Array.isArray(i.antipatterns)?i.antipatterns:[]});}catch{}r.antipatterns.push({...e,added:new Date().toISOString()}),I.writeFileSync(t,q.dump(r,{lineWidth:-1})),V(n);}b();var kt=".paradigm/history";async function _t(n){let e=E.join(n,kt);if(!I.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([un(e),gn(e)]);return {index:o,validation:t}}async function un(n){let e=E.join(n,"index.yaml");if(!I.existsSync(e))return null;try{let o=I.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing index.yaml",{error:o.message}),null}}async function gn(n){let e=E.join(n,"validation.yaml");if(!I.existsSync(e))return null;try{let o=I.readFileSync(e,"utf8");return q.load(o)}catch(o){return a$1.component("#history-loader").error("Error parsing validation.yaml",{error:o.message}),null}}function xo(n,e){return e.map(o=>yn(n,o))}function yn(n,e){let o=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let s of n.index.co_changes)if(s.symbols.includes(e))for(let i of s.symbols)i!==e&&!t.includes(i)&&t.push(i);}let r=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:o,recent:o?.recent||[],co_changes:t,validation:r}}function vo(n,e){let o=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let i of e){let a=n.index.by_symbol?.[i];a&&(a.fragility==="high"||a.fragility==="critical")&&o.push({symbol:i,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(l=>l.symbol===i);c&&!o.find(l=>l.symbol===i)&&o.push(c);}for(let i of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(i));if(a?.length)for(let c of a){let l=c.symbols.filter(p=>p!==i&&!e.includes(p));l.length>0&&c.correlation>.7&&t.push(`${i} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let r=o.filter(i=>i.fragility==="critical").length===0,s=[];return o.length>0&&(s.push("Consider adding extra test coverage before modifying fragile symbols"),s.push("Review recent rollbacks and failures for these symbols")),t.length>0&&s.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:o,warnings:t,safe_to_modify:r,recommendations:s}}async function hn(n,e){let o=E.join(n,kt),t=E.join(o,"log.jsonl");I.existsSync(o)||I.mkdirSync(o,{recursive:true});let r=bn(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
4
4
  `;return I.appendFileSync(t,a),r}async function ko(n,e,o,t){return hn(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function bn(n){let e=1;return I.existsSync(n)&&(e=I.readFileSync(n,"utf8").split(`
5
- `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Ao(n){let e=E.resolve(n),o=await i(e),t=j$1(o),r=null,s=E.join(e,"portal.yaml");if(I.existsSync(s))try{r=await g(s);}catch(p){let f=p?.name??"Error";a$1.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:f});}let i$1=E.basename(e),a=E.join(e,".premise");if(I.existsSync(a))try{let f=I.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);f&&(i$1=f[1].trim());}catch{}let c=null,l=E.join(e,".paradigm","config.yaml");if(I.existsSync(l))try{let p=I.readFileSync(l,"utf8"),f=q.load(p);f&&typeof f=="object"&&(f.version||a$1.component("#index-loader").warn('config.yaml missing "version" field'),f.project||a$1.component("#index-loader").warn('config.yaml missing "project" field')),f&&typeof f.workspace=="string"&&(c=at(e,f.workspace));}catch(p){a$1.component("#index-loader").warn("Failed to load workspace config",{error:p.message});}return {rootDir:e,index:t,aggregation:o,gateConfig:r,projectName:i$1,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function fe(n){return n.wisdom||(n.wisdom=await wt(n.rootDir)),n.wisdom}async function Oo(n){return n.history||(n.history=await _t(n.rootDir)),n.history}j();b();var Pt=false;function Jo(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Dt(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await fe(o),i=St(s,t),a={symbols:t,wisdom:i.map(p=>({symbol:p.symbol,preferences:p.preferences,antipatterns:p.antipatterns.map(f=>({id:f.id,description:f.description,reason:f.reason,alternative:f.alternative,scope:f.scope||"project"})),decisions:p.decisions.map(f=>({id:f.id,title:f.title,status:f.status,decision:f.decision,scope:f.scope||"project"})),experts:p.experts.map(f=>f.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((p,f)=>p+f.antipatterns.length,0),l=i.reduce((p,f)=>p+f.decisions.length,0);a.summary={symbols_with_preferences:i.filter(p=>p.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(p=>p.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let p={},f=[];for(let k of t){let w=await a$3(o.rootDir,{symbol:k,hasAssessment:!0,limit:100});if(w.length===0)continue;let x={correct:0,partial:0,incorrect:0},y=0,j=0;for(let F of w){let $=F.assessment.verdict;x[$]++,F.confidence!=null&&(y+=F.confidence,j++);}p[k]={total:w.length,...x,avgConfidence:j>0?Math.round(y/j*1e3)/1e3:null};let N=(x.correct+x.partial*.5)/w.length;N<.6&&w.length>=3&&f.push(`Low historical accuracy for ${k}: ${Math.round(N*100)}% across ${w.length} entries. Proceed with extra caution.`);}Object.keys(p).length>0&&(a.calibration=p),f.length>0&&(a.calibration_warnings=f);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:t,id:r,symbols:s,description:i,reason:a,alternative:c,title:l,status:p,rationale:f,consequences:k,scope:w="project"}=e$1;if(t==="antipattern"){if(!i||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let x={id:r,symbols:s,description:i,reason:a,alternative:c};return w==="global"?g$1(x):await vt(o.rootDir,x),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:w,message:`Antipattern recorded to ${w} scope`})}}if(t==="decision"){if(!l||!i||!f||!k)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(Pt||(Pt=true,a$1.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),w==="global"){let j={id:r,title:l,status:p||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:f,consequences:k};return h(j),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let x=a$2(o.rootDir,{title:l,decision:i,rationale:{factors:f.factors,conclusion:f.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:p==="accepted"?"active":p==="proposed"?"proposed":"active",context:a||void 0,consequences:k,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),y=d$1(o.rootDir,x.id);return V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:x.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${x.id})`,...y?{companion_lore_id:y}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:r}=e$1,s=await fe(o),i=E.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(l=>l.id===r);return a?d().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g$1({...a,learned_from:`promoted from ${i}`}),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(l=>l.id===r);return a?e().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await fe(o),i=xt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Uo(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Rt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await I$1(o.rootDir,t,r);return s.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:s.length,task:t,matches:s.map(i=>({id:i.protocol.id,name:i.protocol.name,description:i.protocol.description,score:i.score,status:i.protocol.status,exemplar:i.protocol.exemplar,last_verified:i.protocol.last_verified,steps:i.protocol.steps.map(wn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await G(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=L(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await J(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await K(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await G(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=L(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s=(await F(o.rootDir)).map(a=>{let c=L(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s.length,current:s.filter(a=>a.status==="current").length,stale:s.filter(a=>a.status==="stale").length,broken:s.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s,health:i},null,2)}}default:return {handled:false,text:""}}}function wn(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}j();var ee=null,ke=false;async function _e(n){if(ee)ke||(await ee.ensureReady(),ke=true);else {let e=E.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function Sn(n,e){return (await _e(n)).recordPracticeEvent(e)}async function Ko(n,e){return (await _e(n)).getPracticeEvents(e)}async function Ce(n,e){return (await _e(n)).getComplianceRate(e)}async function It(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await Ce(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Qo(n,e,o){let t=[];for(let r of e){let s=await Sn(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function At(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var me={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function Ot(){let n=process.env.PARADIGM_AUTHOR;if(n)return Pe(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Pe(e)}catch{}try{let e=Et.userInfo().username;if(e)return Pe(e)}catch{}return "unknown"}function Pe(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function is(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function je(n,e,o){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(Nt)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:p,lines_removed:f,commit:k,duration_minutes:w,decisions:x,errors_encountered:y,learnings:j,verification:N$1,tags:F,meta:$,body:A,linked_lore:d,linked_tasks:_,linked_commits:O,confidence:u}=e;if(t==="decision")return a$1.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:me.removed_in,successor_tool:me.successor_tool}),At(me);let P;try{let S=new Date(Date.now()-2592e6).toISOString(),h=await Ce(o.rootDir,{dateFrom:S});if(h.total>0){let m=(await It(o.rootDir,{dateFrom:S})).filter(C=>C.rate<60).map(C=>C.category);P={rate:h.rate,followed:h.followed,skipped:h.skipped,partial:h.partial,weakAreas:m.length>0?m:void 0};}}catch{}let v={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:w,author:Ot(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:p,lines_removed:f,commit:k,decisions:x,errors_encountered:y,learnings:j,verification:N$1,tags:F,meta:$||void 0,habit_compliance:P,body:A,linked_lore:d,linked_tasks:_,linked_commits:O,confidence:u!=null&&u>=0&&u<=1?u:void 0},b=await d$2(o.rootDir,v);j$2().setLastLoreEntryId(b);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:h}=await import('./agent-loader-W3RQJVW7.js');h(o.rootDir,S,{symbols_touched:i,confidence:u!=null&&u>=0&&u<=1?u:void 0});}}catch{}let D=null;try{c&&c.length>=2&&(D=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,h=S==="auto"?vn(e):S;try{if(h==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:v.agent?.model||"unknown",summary:v.summary,outcome:v.verification?.status==="pass"?"pass":v.verification?.status==="fail"?"fail":"partial",files_modified:v.files_modified,symbols_touched:v.symbols_touched,commit:v.commit,linked_lore:v.id||b}),T="work-log";}else if(h==="journal"&&v.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-CNNA4EAU.js');for(let m of v.learnings)g(v.agent?.model||"unknown",{trigger:"self_reflection",insight:m,project:o.projectName||"unknown",transferable:!1,linked_work_log:v.id||b});T="journal";}else if(h==="decision"&&v.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let m of v.decisions)g(o.rootDir,{title:m.decision.slice(0,100),decision:m.decision,rationale:m.rationale,participants:[{id:`agent/${v.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:v.symbols_touched,status:"active",linked_lore:v.id||b});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:b,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...D?{protocol_suggestion:D}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,r=await c(o.rootDir),s=await a$3(o.rootDir,{limit:t}),i={};for(let l of s)for(let p of l.symbols_touched)i[p]=(i[p]||0)+1;let a=Object.entries(i).sort(([,l],[,p])=>p-l).slice(0,10).map(([l,p])=>({symbol:l,count:p})),c$1={};for(let l of s){let p=l.author;c$1[p]||(c$1[p]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[p].count++,l.agent&&(c$1[p].hasAgent=true),l.timestamp>c$1[p].lastActive&&(c$1[p].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(Nt),hotSymbols:a,authors:Object.entries(c$1).map(([l,p])=>({id:l,hasAgent:p.hasAgent,entries:p.count,lastActive:p.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,r=await b$1(o.rootDir,t);return r?{handled:true,text:JSON.stringify(r,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:r,...s}=e,i={};for(let[c,l]of Object.entries(s))l!==void 0&&(i[c]=l);let a=await g$2(o.rootDir,t,i);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,r=e.verdict,s=e.notes,i=await b$1(o.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:r,assessed_by:Ot(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let k=process.env.PARADIGM_AGENT_ID;if(k&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:w}=await import('./agent-loader-W3RQJVW7.js');w(o.rootDir,k,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,p=i.confidence!=null?l-i.confidence:null,f=p!=null?p>.1?"Under-confident (actual outcome better than predicted)":p<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:t,verdict:r,confidence:i.confidence??null,delta:p,deltaDescription:f,message:c?`Assessment recorded: ${r}${p!=null?` (delta: ${p>0?"+":""}${p.toFixed(2)})`:""}`:`Failed to assess: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},r=await a$3(o.rootDir,t),s=r.filter(A=>A.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,p=0,f=0;for(let A of r){let d=A.assessment.verdict;c[d]++;let _=d==="correct"?1:d==="partial"?.5:0;l+=_,A.confidence!=null&&(p+=A.confidence,f+=Math.abs(_-A.confidence));}let k=i>0?l/i:0,w=a>0?p/a:null,x=a>0?l/i-p/a:null,y=a>0?1-f/a:null,j=e.groupBy,N;if(j&&i>0){let A=new Map;for(let d of r){let _=[];j==="symbol"?_=d.symbols_touched||[]:j==="tag"?_=d.tags||[]:j==="type"&&(_=[d.type||"agent-session"]);for(let O of _)A.has(O)||A.set(O,[]),A.get(O).push(d);}N=Array.from(A.entries()).map(([d,_])=>{let O=_.filter(D=>D.confidence!=null),u={correct:0,partial:0,incorrect:0},P=0,v=0,b=0;for(let D of _){let T=D.assessment.verdict;u[T]++;let S=T==="correct"?1:T==="partial"?.5:0;P+=S,D.confidence!=null&&(v+=D.confidence,b+=Math.abs(S-D.confidence));}return {key:d,total:_.length,accuracyRate:P/_.length,avgConfidence:O.length>0?v/O.length:null,calibrationScore:O.length>0?1-b/O.length:null,verdictBreakdown:u}}).sort((d,_)=>_.total-d.total);}let F=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&F.push($),y!=null&&(y>=.9?F.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?F.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.5?F.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):F.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?F.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&F.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&F.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(k*1e3)/1e3,avgConfidence:w!=null?Math.round(w*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*1e3)/1e3:null,verdictBreakdown:c,...N?{groups:N}:{},insights:F},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let s=await i$1(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function vn(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function Nt(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function Ss(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function xs(n,e,o){return n==="paradigm_captain_brief"?kn(e,o):n==="paradigm_captain_debrief"?_n(e,o):n==="paradigm_captain_board"?Dn(e,o):{handled:false,text:""}}async function kn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=E.join(e.rootDir,".paradigm"),i=E.join(s,".cid-session"),a=E.join(s,".cid-briefed");try{I.existsSync(a)&&I.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};I.mkdirSync(s,{recursive:!0}),I.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=Tn(o),l=[],p=new Set;for(let S of t)if(!p.has(S)){p.add(S);let h=Wt(S);l.push({id:S,type:h,description:"Provided as anchor symbol"});}let f=[];try{for(let S of c.slice(0,3)){let g=m(e.index,S).slice(0,5);for(let m of g)if(!p.has(m.symbol)){p.add(m.symbol);let C=Ln(m.type);l.push({id:m.symbol,type:C,description:m.description||"",file:m.file}),f.push(m.symbol);}}}catch{}let k={directories:[],files:[]};try{let S=await pt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let h=JSON.parse(S.text);if(h.files)for(let g of h.files){let m=typeof g=="string"?g:g.path||g.file||"";m&&k.files.push(m);}if(h.directories)for(let g of h.directories){let m=typeof g=="string"?g:g.path||g.directory||"";m&&k.directories.push(m);}if(h.symbols)for(let g of h.symbols){let m=typeof g=="string"?g:g.id;m&&!p.has(m)&&(p.add(m),l.push({id:m,type:Wt(m),description:typeof g=="object"&&g.description||""}));}}}catch{}let w=new Set(k.directories);for(let S of k.files){let h=E.dirname(S);h&&h!=="."&&w.add(h);}let x=l.slice(0,r==="deep"?5:3),y={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let h=await le("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(h.handled){let g=JSON.parse(h.text);if(g.analysis){for(let m of g.analysis.directlyAffected||[]){let C=m.symbol||m;C&&!y.affectedSymbols.includes(C)&&y.affectedSymbols.push(C);}for(let m of g.analysis.indirectlyAffected||[])m&&!y.affectedSymbols.includes(m)&&y.affectedSymbols.push(m);}if(g.affectedFlows?.affectedFlows)for(let m of g.affectedFlows.affectedFlows){let C=m.flowId||m;C&&!y.affectedFlows.includes(C)&&y.affectedFlows.push(C);}if(g.affectedGates)for(let m of g.affectedGates){let C=m.gate||m;C&&!y.affectedGates.includes(C)&&y.affectedGates.push(C);}g.impact==="high"&&(y.fragileSymbols.includes(S.id)||y.fragileSymbols.push(S.id));}}catch{}let j=[],N=Wn(o);if(N.length>0)try{let{handleGatesForRoute:S}=await import('./tools-NOMEIBS7.js').catch(()=>({handleGatesForRoute:null})),h=E.join(e.rootDir,"portal.yaml");if(I.existsSync(h)){let g=I.readFileSync(h,"utf8");for(let m of N){let C=g.includes(m);j.push({route:m,gate:"^authenticated",declared:C});}}else for(let g of N)j.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let F=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),h=await Dt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(h.handled){let g=JSON.parse(h.text);if(g.antipatterns)for(let m of g.antipatterns.slice(0,3)){let C=m.pattern||m.description||m.text||String(m);C&&!F.includes(C)&&F.push(C);}if(g.wisdom?.antipatterns)for(let m of g.wisdom.antipatterns.slice(0,3)){let C=m.pattern||m.description||String(m);C&&!F.includes(C)&&F.push(C);}}}catch{}let $={matched:false};try{let S=await Rt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let h=JSON.parse(S.text),g=h.matches||h.protocols||h.results||[];if(g.length>0){let m=g[0];$={matched:!0,id:m.id,name:m.name||m.title,steps:(m.steps||[]).slice(0,5).map(C=>typeof C=="string"?C:C.description||String(C))};}}}catch{}let A=[];if(r!=="quick")try{let S=l[0]?.id,h={limit:r==="deep"?5:3};S&&(h.symbol=S);let g=await je("paradigm_lore_search",h,e);if(g.handled){let C=JSON.parse(g.text).entries||[];for(let B of C.slice(0,3))A.push({id:B.id,summary:(B.summary||B.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let d=Array.from(w),_=0;for(let S of d){let h=E.join(e.rootDir,S,".purpose");if(I.existsSync(h))try{I.readFileSync(h,"utf8").trim().length>50&&_++;}catch{}}let O$1=d.length>0?_/d.length:.5,u=Hn(O$1),P=Mn(O$1,u,d.length),v=y.affectedSymbols.length+k.files.length,b=v>20?"large":v>8?"medium":v>2?"small":"tiny",D={territory:{directories:d.slice(0,10),files:k.files.slice(0,10),estimatedScope:b},symbols:l.slice(0,10),blastRadius:y,gates:j,protocol:$,warnings:F,coverage:{score:O$1,label:u,note:P},loreRefs:A,archMap:b$2(e.rootDir),renderedBrief:""};D.renderedBrief=Bn(D);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:O$1};I.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(D,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function _n(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=E.join(e.rootDir,".paradigm"),c=E.join(a,".cid-briefed"),l=E.join(a,".pending-review"),p=new Set;for(let b of r){let D=E.dirname(b);D&&D!=="."&&p.add(D);}let f=0,k=p.size;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(I.existsSync(D))try{I.readFileSync(D,"utf8").trim().length>50&&f++;}catch{}}let w=k>0?f/k:1,x=[],y=[];for(let b of p){let D=E.join(e.rootDir,b,".purpose"),T=E.join(e.rootDir,b),S=false;if(I.existsSync(D))try{S=I.readFileSync(D,"utf8").trim().length>50;}catch{}if(S){if(r.some(g=>E.dirname(g)===b&&s.length>0)){y.push(b);try{let g=JSON.stringify({path:b,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});I.appendFileSync(l,g+`
5
+ `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function Ao(n){let e=E.resolve(n),o=await i(e),t=j$1(o),r=null,s=E.join(e,"portal.yaml");if(I.existsSync(s))try{r=await g(s);}catch(p){let f=p?.name??"Error";a$1.component("#index-loader").warn("Could not parse portal.yaml",{errorClass:f});}let i$1=E.basename(e),a=E.join(e,".premise");if(I.existsSync(a))try{let f=I.readFileSync(a,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);f&&(i$1=f[1].trim());}catch{}let c=null,l=E.join(e,".paradigm","config.yaml");if(I.existsSync(l))try{let p=I.readFileSync(l,"utf8"),f=q.load(p);f&&typeof f=="object"&&(f.version||a$1.component("#index-loader").warn('config.yaml missing "version" field'),f.project||a$1.component("#index-loader").warn('config.yaml missing "project" field')),f&&typeof f.workspace=="string"&&(c=at(e,f.workspace));}catch(p){a$1.component("#index-loader").warn("Failed to load workspace config",{error:p.message});}return {rootDir:e,index:t,aggregation:o,gateConfig:r,projectName:i$1,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function fe(n){return n.wisdom||(n.wisdom=await wt(n.rootDir)),n.wisdom}async function Oo(n){return n.history||(n.history=await _t(n.rootDir)),n.history}j();b();var Pt=false;function Jo(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Dt(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await fe(o),i=St(s,t),a={symbols:t,wisdom:i.map(p=>({symbol:p.symbol,preferences:p.preferences,antipatterns:p.antipatterns.map(f=>({id:f.id,description:f.description,reason:f.reason,alternative:f.alternative,scope:f.scope||"project"})),decisions:p.decisions.map(f=>({id:f.id,title:f.title,status:f.status,decision:f.decision,scope:f.scope||"project"})),experts:p.experts.map(f=>f.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((p,f)=>p+f.antipatterns.length,0),l=i.reduce((p,f)=>p+f.decisions.length,0);a.summary={symbols_with_preferences:i.filter(p=>p.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(p=>p.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let p={},f=[];for(let k of t){let w=await a$3(o.rootDir,{symbol:k,hasAssessment:!0,limit:100});if(w.length===0)continue;let x={correct:0,partial:0,incorrect:0},y=0,j=0;for(let F of w){let $=F.assessment.verdict;x[$]++,F.confidence!=null&&(y+=F.confidence,j++);}p[k]={total:w.length,...x,avgConfidence:j>0?Math.round(y/j*1e3)/1e3:null};let N=(x.correct+x.partial*.5)/w.length;N<.6&&w.length>=3&&f.push(`Low historical accuracy for ${k}: ${Math.round(N*100)}% across ${w.length} entries. Proceed with extra caution.`);}Object.keys(p).length>0&&(a.calibration=p),f.length>0&&(a.calibration_warnings=f);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:t,id:r,symbols:s,description:i,reason:a,alternative:c,title:l,status:p,rationale:f,consequences:k,scope:w="project"}=e$1;if(t==="antipattern"){if(!i||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let x={id:r,symbols:s,description:i,reason:a,alternative:c};return w==="global"?g$1(x):await vt(o.rootDir,x),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:w,message:`Antipattern recorded to ${w} scope`})}}if(t==="decision"){if(!l||!i||!f||!k)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(Pt||(Pt=true,a$1.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),w==="global"){let j={id:r,title:l,status:p||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a||"",decision:i,rationale:f,consequences:k};return h(j),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let x=a$2(o.rootDir,{title:l,decision:i,rationale:{factors:f.factors,conclusion:f.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:p==="accepted"?"active":p==="proposed"?"proposed":"active",context:a||void 0,consequences:k,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),y=d$1(o.rootDir,x.id);return V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:x.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${x.id})`,...y?{companion_lore_id:y}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:r}=e$1,s=await fe(o),i=E.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(l=>l.id===r);return a?d().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g$1({...a,learned_from:`promoted from ${i}`}),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(l=>l.id===r);return a?e().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),V(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await fe(o),i=xt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function Uo(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Rt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await I$1(o.rootDir,t,r);return s.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:s.length,task:t,matches:s.map(i=>({id:i.protocol.id,name:i.protocol.name,description:i.protocol.description,score:i.score,status:i.protocol.status,exemplar:i.protocol.exemplar,last_verified:i.protocol.last_verified,steps:i.protocol.steps.map(wn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await G(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=L(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await J(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await K(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await G(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=L(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s=(await F(o.rootDir)).map(a=>{let c=L(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s.length,current:s.filter(a=>a.status==="current").length,stale:s.filter(a=>a.status==="stale").length,broken:s.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s,health:i},null,2)}}default:return {handled:false,text:""}}}function wn(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}j();var ee=null,ke=false;async function _e(n){if(ee)ke||(await ee.ensureReady(),ke=true);else {let e=E.join(n,".paradigm","sentinel","sentinel.db");ee=new f(e),await ee.ensureReady(),ke=true;}return ee}async function Sn(n,e){return (await _e(n)).recordPracticeEvent(e)}async function Ko(n,e){return (await _e(n)).getPracticeEvents(e)}async function Ce(n,e){return (await _e(n)).getComplianceRate(e)}async function It(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await Ce(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Qo(n,e,o){let t=[];for(let r of e){let s=await Sn(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function At(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var me={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function Ot(){let n=process.env.PARADIGM_AUTHOR;if(n)return Pe(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Pe(e)}catch{}try{let e=Et.userInfo().username;if(e)return Pe(e)}catch{}return "unknown"}function Pe(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function is(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function je(n,e,o){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(Nt)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:p,lines_removed:f,commit:k,duration_minutes:w,decisions:x,errors_encountered:y,learnings:j,verification:N$1,tags:F,meta:$,body:A,linked_lore:d,linked_tasks:_,linked_commits:O,confidence:u}=e;if(t==="decision")return a$1.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:me.removed_in,successor_tool:me.successor_tool}),At(me);let P;try{let S=new Date(Date.now()-2592e6).toISOString(),h=await Ce(o.rootDir,{dateFrom:S});if(h.total>0){let m=(await It(o.rootDir,{dateFrom:S})).filter(C=>C.rate<60).map(C=>C.category);P={rate:h.rate,followed:h.followed,skipped:h.skipped,partial:h.partial,weakAreas:m.length>0?m:void 0};}}catch{}let v={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:w,author:Ot(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a,files_created:c,files_modified:l,lines_added:p,lines_removed:f,commit:k,decisions:x,errors_encountered:y,learnings:j,verification:N$1,tags:F,meta:$||void 0,habit_compliance:P,body:A,linked_lore:d,linked_tasks:_,linked_commits:O,confidence:u!=null&&u>=0&&u<=1?u:void 0},b=await d$2(o.rootDir,v);j$2().setLastLoreEntryId(b);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:h}=await import('./agent-loader-W3RQJVW7.js');h(o.rootDir,S,{symbols_touched:i,confidence:u!=null&&u>=0&&u<=1?u:void 0});}}catch{}let D=null;try{c&&c.length>=2&&(D=N(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,h=S==="auto"?vn(e):S;try{if(h==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:v.agent?.model||"unknown",summary:v.summary,outcome:v.verification?.status==="pass"?"pass":v.verification?.status==="fail"?"fail":"partial",files_modified:v.files_modified,symbols_touched:v.symbols_touched,commit:v.commit,linked_lore:v.id||b}),T="work-log";}else if(h==="journal"&&v.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-CNNA4EAU.js');for(let m of v.learnings)g(v.agent?.model||"unknown",{trigger:"self_reflection",insight:m,project:o.projectName||"unknown",transferable:!1,linked_work_log:v.id||b});T="journal";}else if(h==="decision"&&v.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let m of v.decisions)g(o.rootDir,{title:m.decision.slice(0,100),decision:m.decision,rationale:m.rationale,participants:[{id:`agent/${v.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:v.symbols_touched,status:"active",linked_lore:v.id||b});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:b,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...D?{protocol_suggestion:D}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,r=await c(o.rootDir),s=await a$3(o.rootDir,{limit:t}),i={};for(let l of s)for(let p of l.symbols_touched)i[p]=(i[p]||0)+1;let a=Object.entries(i).sort(([,l],[,p])=>p-l).slice(0,10).map(([l,p])=>({symbol:l,count:p})),c$1={};for(let l of s){let p=l.author;c$1[p]||(c$1[p]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[p].count++,l.agent&&(c$1[p].hasAgent=true),l.timestamp>c$1[p].lastActive&&(c$1[p].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(Nt),hotSymbols:a,authors:Object.entries(c$1).map(([l,p])=>({id:l,hasAgent:p.hasAgent,entries:p.count,lastActive:p.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,r=await b$1(o.rootDir,t);return r?{handled:true,text:JSON.stringify(r,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:r,...s}=e,i={};for(let[c,l]of Object.entries(s))l!==void 0&&(i[c]=l);let a=await g$2(o.rootDir,t,i);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,r=e.verdict,s=e.notes,i=await b$1(o.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:r,assessed_by:Ot(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let k=process.env.PARADIGM_AGENT_ID;if(k&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:w}=await import('./agent-loader-W3RQJVW7.js');w(o.rootDir,k,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,p=i.confidence!=null?l-i.confidence:null,f=p!=null?p>.1?"Under-confident (actual outcome better than predicted)":p<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:t,verdict:r,confidence:i.confidence??null,delta:p,deltaDescription:f,message:c?`Assessment recorded: ${r}${p!=null?` (delta: ${p>0?"+":""}${p.toFixed(2)})`:""}`:`Failed to assess: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},r=await a$3(o.rootDir,t),s=r.filter(A=>A.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,p=0,f=0;for(let A of r){let d=A.assessment.verdict;c[d]++;let _=d==="correct"?1:d==="partial"?.5:0;l+=_,A.confidence!=null&&(p+=A.confidence,f+=Math.abs(_-A.confidence));}let k=i>0?l/i:0,w=a>0?p/a:null,x=a>0?l/i-p/a:null,y=a>0?1-f/a:null,j=e.groupBy,N;if(j&&i>0){let A=new Map;for(let d of r){let _=[];j==="symbol"?_=d.symbols_touched||[]:j==="tag"?_=d.tags||[]:j==="type"&&(_=[d.type||"agent-session"]);for(let O of _)A.has(O)||A.set(O,[]),A.get(O).push(d);}N=Array.from(A.entries()).map(([d,_])=>{let O=_.filter(D=>D.confidence!=null),u={correct:0,partial:0,incorrect:0},P=0,v=0,b=0;for(let D of _){let T=D.assessment.verdict;u[T]++;let S=T==="correct"?1:T==="partial"?.5:0;P+=S,D.confidence!=null&&(v+=D.confidence,b+=Math.abs(S-D.confidence));}return {key:d,total:_.length,accuracyRate:P/_.length,avgConfidence:O.length>0?v/O.length:null,calibrationScore:O.length>0?1-b/O.length:null,verdictBreakdown:u}}).sort((d,_)=>_.total-d.total);}let F=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&F.push($),y!=null&&(y>=.9?F.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):y>=.7?F.push("Good calibration \u2014 some room for improvement in confidence estimates."):y>=.5?F.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):F.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?F.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&F.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&F.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(k*1e3)/1e3,avgConfidence:w!=null?Math.round(w*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:y!=null?Math.round(y*1e3)/1e3:null,verdictBreakdown:c,...N?{groups:N}:{},insights:F},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let s=await i$1(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function vn(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function Nt(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function Ss(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function xs(n,e,o){return n==="paradigm_captain_brief"?kn(e,o):n==="paradigm_captain_debrief"?_n(e,o):n==="paradigm_captain_board"?Dn(e,o):{handled:false,text:""}}async function kn(n,e){let o=n.taskDescription,t=n.symbols||[],r=n.depth||"standard",s=E.join(e.rootDir,".paradigm"),i=E.join(s,".cid-session"),a=E.join(s,".cid-briefed");try{I.existsSync(a)&&I.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};I.mkdirSync(s,{recursive:!0}),I.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=Tn(o),l=[],p=new Set;for(let S of t)if(!p.has(S)){p.add(S);let h=Wt(S);l.push({id:S,type:h,description:"Provided as anchor symbol"});}let f=[];try{for(let S of c.slice(0,3)){let g=m(e.index,S).slice(0,5);for(let m of g)if(!p.has(m.symbol)){p.add(m.symbol);let C=Ln(m.type);l.push({id:m.symbol,type:C,description:m.description||"",file:m.file}),f.push(m.symbol);}}}catch{}let k={directories:[],files:[]};try{let S=await pt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let h=JSON.parse(S.text);if(h.files)for(let g of h.files){let m=typeof g=="string"?g:g.path||g.file||"";m&&k.files.push(m);}if(h.directories)for(let g of h.directories){let m=typeof g=="string"?g:g.path||g.directory||"";m&&k.directories.push(m);}if(h.symbols)for(let g of h.symbols){let m=typeof g=="string"?g:g.id;m&&!p.has(m)&&(p.add(m),l.push({id:m,type:Wt(m),description:typeof g=="object"&&g.description||""}));}}}catch{}let w=new Set(k.directories);for(let S of k.files){let h=E.dirname(S);h&&h!=="."&&w.add(h);}let x=l.slice(0,r==="deep"?5:3),y={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let h=await le("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(h.handled){let g=JSON.parse(h.text);if(g.analysis){for(let m of g.analysis.directlyAffected||[]){let C=m.symbol||m;C&&!y.affectedSymbols.includes(C)&&y.affectedSymbols.push(C);}for(let m of g.analysis.indirectlyAffected||[])m&&!y.affectedSymbols.includes(m)&&y.affectedSymbols.push(m);}if(g.affectedFlows?.affectedFlows)for(let m of g.affectedFlows.affectedFlows){let C=m.flowId||m;C&&!y.affectedFlows.includes(C)&&y.affectedFlows.push(C);}if(g.affectedGates)for(let m of g.affectedGates){let C=m.gate||m;C&&!y.affectedGates.includes(C)&&y.affectedGates.push(C);}g.impact==="high"&&(y.fragileSymbols.includes(S.id)||y.fragileSymbols.push(S.id));}}catch{}let j=[],N=Wn(o);if(N.length>0)try{let{handleGatesForRoute:S}=await import('./tools-Z354SXGS.js').catch(()=>({handleGatesForRoute:null})),h=E.join(e.rootDir,"portal.yaml");if(I.existsSync(h)){let g=I.readFileSync(h,"utf8");for(let m of N){let C=g.includes(m);j.push({route:m,gate:"^authenticated",declared:C});}}else for(let g of N)j.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let F=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),h=await Dt("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(h.handled){let g=JSON.parse(h.text);if(g.antipatterns)for(let m of g.antipatterns.slice(0,3)){let C=m.pattern||m.description||m.text||String(m);C&&!F.includes(C)&&F.push(C);}if(g.wisdom?.antipatterns)for(let m of g.wisdom.antipatterns.slice(0,3)){let C=m.pattern||m.description||String(m);C&&!F.includes(C)&&F.push(C);}}}catch{}let $={matched:false};try{let S=await Rt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let h=JSON.parse(S.text),g=h.matches||h.protocols||h.results||[];if(g.length>0){let m=g[0];$={matched:!0,id:m.id,name:m.name||m.title,steps:(m.steps||[]).slice(0,5).map(C=>typeof C=="string"?C:C.description||String(C))};}}}catch{}let A=[];if(r!=="quick")try{let S=l[0]?.id,h={limit:r==="deep"?5:3};S&&(h.symbol=S);let g=await je("paradigm_lore_search",h,e);if(g.handled){let C=JSON.parse(g.text).entries||[];for(let B of C.slice(0,3))A.push({id:B.id,summary:(B.summary||B.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let d=Array.from(w),_=0;for(let S of d){let h=E.join(e.rootDir,S,".purpose");if(I.existsSync(h))try{I.readFileSync(h,"utf8").trim().length>50&&_++;}catch{}}let O$1=d.length>0?_/d.length:.5,u=Hn(O$1),P=Mn(O$1,u,d.length),v=y.affectedSymbols.length+k.files.length,b=v>20?"large":v>8?"medium":v>2?"small":"tiny",D={territory:{directories:d.slice(0,10),files:k.files.slice(0,10),estimatedScope:b},symbols:l.slice(0,10),blastRadius:y,gates:j,protocol:$,warnings:F,coverage:{score:O$1,label:u,note:P},loreRefs:A,archMap:b$2(e.rootDir),renderedBrief:""};D.renderedBrief=Bn(D);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:O$1};I.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(D,null,2);return O(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function _n(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a=E.join(e.rootDir,".paradigm"),c=E.join(a,".cid-briefed"),l=E.join(a,".pending-review"),p=new Set;for(let b of r){let D=E.dirname(b);D&&D!=="."&&p.add(D);}let f=0,k=p.size;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(I.existsSync(D))try{I.readFileSync(D,"utf8").trim().length>50&&f++;}catch{}}let w=k>0?f/k:1,x=[],y=[];for(let b of p){let D=E.join(e.rootDir,b,".purpose"),T=E.join(e.rootDir,b),S=false;if(I.existsSync(D))try{S=I.readFileSync(D,"utf8").trim().length>50;}catch{}if(S){if(r.some(g=>E.dirname(g)===b&&s.length>0)){y.push(b);try{let g=JSON.stringify({path:b,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});I.appendFileSync(l,g+`
6
6
  `,"utf8");}catch{}}}else try{if(!I.existsSync(T))continue;let h=E.basename(b),g=Jn(h,b,r);I.writeFileSync(D,g,"utf8"),x.push(b),y.push(b);try{let m=JSON.stringify({path:b,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(C=>E.dirname(C)===b).join(", ")}`,timestamp:new Date().toISOString()});I.appendFileSync(l,m+`
7
- `,"utf8");}catch{}}catch{}}let j=0;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(I.existsSync(D))try{I.readFileSync(D,"utf8").trim().length>50&&j++;}catch{}}let N=k>0?j/k:1,F="";try{let b=await je("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${t.slice(0,80)}`,summary:t,symbols_touched:s,files_modified:r,tags:["arc:cid-debrief",`orch:${o}`],meta:{orchestrationId:o,coverageScore:{before:w,after:N},coverageAdded:x,...i?{notes:i}:{}}},e);if(b.handled){let D=JSON.parse(b.text);F=D.id||D.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=jn(a),!$.ranThisSession)try{let{runPostflightLearning:b}=await import('./ambient-OW5M5LVN.js');await b(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a$1.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(b){$.selfHealError=b instanceof Error?b.message:String(b),a$1.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:D}=await import('./propose-block-ZEMEWJQF.js');await D("paradigm_propose_block",{claimant:"navigation",severity:"advise",reason:`Postflight learning did not run and Cid's self-heal failed: ${$.selfHealError}`,unblock_hint:"Run `paradigm_ambient_learn_postflight` manually, or inspect .paradigm/events/settlement-liveness.jsonl for the severed stage."},e),$.blockProposed=!0;}catch{}}let A=false;try{let b={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:N};I.mkdirSync(a,{recursive:!0}),I.writeFileSync(c,JSON.stringify(b,null,2),"utf8"),A=!0;}catch{}let d={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:w,after:N},newSymbols:s,touchedFiles:r,notes:i||""};try{let b=E.join(a,"events","session-log.jsonl");if(I.existsSync(b)){let S=I.readFileSync(b,"utf8").split(`
7
+ `,"utf8");}catch{}}catch{}}let j=0;for(let b of p){let D=E.join(e.rootDir,b,".purpose");if(I.existsSync(D))try{I.readFileSync(D,"utf8").trim().length>50&&j++;}catch{}}let N=k>0?j/k:1,F="";try{let b=await je("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${t.slice(0,80)}`,summary:t,symbols_touched:s,files_modified:r,tags:["arc:cid-debrief",`orch:${o}`],meta:{orchestrationId:o,coverageScore:{before:w,after:N},coverageAdded:x,...i?{notes:i}:{}}},e);if(b.handled){let D=JSON.parse(b.text);F=D.id||D.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=jn(a),!$.ranThisSession)try{let{runPostflightLearning:b}=await import('./ambient-W3SPKLKC.js');await b(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a$1.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(b){$.selfHealError=b instanceof Error?b.message:String(b),a$1.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:D}=await import('./propose-block-ZEMEWJQF.js');await D("paradigm_propose_block",{claimant:"navigation",severity:"advise",reason:`Postflight learning did not run and Cid's self-heal failed: ${$.selfHealError}`,unblock_hint:"Run `paradigm_ambient_learn_postflight` manually, or inspect .paradigm/events/settlement-liveness.jsonl for the severed stage."},e),$.blockProposed=!0;}catch{}}let A=false;try{let b={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:N};I.mkdirSync(a,{recursive:!0}),I.writeFileSync(c,JSON.stringify(b,null,2),"utf8"),A=!0;}catch{}let d={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:w,after:N},newSymbols:s,touchedFiles:r,notes:i||""};try{let b=E.join(a,"events","session-log.jsonl");if(I.existsSync(b)){let S=I.readFileSync(b,"utf8").split(`
8
8
  `).filter(g=>g.trim().length>0).slice(-50),h=new Map;for(let g of S)try{let m=JSON.parse(g),C=m.agentId||m.agent||m.role||"";if(!C)continue;h.has(C)||h.set(C,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let B=h.get(C),De=m.action||m.event||m.message||"";if(De&&B.contributions.push(String(De).slice(0,120)),Array.isArray(m.symbols))for(let te of m.symbols)B.symbolsTouched.add(String(te));let Re=m.symbol||"";if(Re&&B.symbolsTouched.add(Re),Array.isArray(m.patterns))for(let te of m.patterns)B.patternsObserved.includes(String(te))||B.patternsObserved.push(String(te));}catch{}for(let[g,m]of h.entries())d.agentContributions.push({agentId:g,contribution:m.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(m.symbolsTouched).slice(0,10),patternsObserved:m.patternsObserved.slice(0,5)});}}catch{}let _=d.agentContributions.length;d.agentContributions.length===0&&d.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]}),_>0&&a$4(e.rootDir,{verdicts:_,source:"debrief"});let O$1={coverageAdded:x,delegatedToDocumentor:y,loreEntryId:F,coverageScore:{before:w,after:N,delta:N-w},stopHookCleared:A,postflight:$,sessionInsights:d},u=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
9
9
  `),v=JSON.stringify(O$1,null,2)+`
10
10
  `+u;return O(v.length,"paradigm_captain_debrief"),{handled:true,text:v}}var Cn=E.join("events","settlement-liveness.jsonl"),Pn=360*60*1e3;function jn(n){let e=E.join(n,Cn);if(!I.existsSync(e))return false;try{let t=I.readFileSync(e,"utf8").split(`
11
- `).filter(s=>s.trim().length>0),r=Date.now()-Pn;for(let s of t.slice(-50))try{let i=JSON.parse(s),a=i.ts?new Date(i.ts).getTime():NaN;if(Number.isNaN(a)||a<r)continue;if(i.stages?.runPostflightLearning==="ok")return !0}catch{}}catch{return false}return false}async function Dn(n,e){let o=n.action||"read";if(o==="claim")return En(n,e);if(o==="advance")return $n(n,e);let t=await On(e.rootDir,{},e),r=JSON.stringify(t,null,2);return O(r.length,"paradigm_captain_board"),{handled:true,text:r}}function Rn(n,e){return n.settledAt?n.crashed_at||e.some(t=>t.crashed_at)?"crashed":"settled":e.length===0?"pending":e.some(t=>t.status==="in-progress")||n.status==="in-progress"?"in-progress":"pending"}function Fn(n){return [...n].sort((e,o)=>{let t=e.stage??0,r=o.stage??0;if(t!==r)return t-r;let s=e.dependsOn?.length??0,i=o.dependsOn?.length??0;return s!==i?s-i:e.id.localeCompare(o.id)})}async function $t(n,e){let o=Lt(n).slice(0,3),t=[];for(let r of o)try{let s=await le("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var In=/[#$^!~][a-z][a-z0-9-]*/gi;function Lt(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(In)||[];for(let t of o)e.add(t);return Array.from(e)}async function An(n,e){let o=Lt(n).slice(0,3),t=0,r=[];for(let s of o)try{let i=await le("paradigm_ripple",{symbol:s,depth:2,response_format:"concise"},e);if(i.handled){let a=JSON.parse(i.text),c=a.analysis?.directlyAffected?.length??0,l=a.analysis?.indirectlyAffected?.length??0;t+=c*2+l,a.impact==="high"&&!r.includes(s)&&r.push(s);}}catch{}return {score:t,fragile:r}}var Tt={high:0,medium:1,low:2};async function On(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-LFEE6OU7.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(d){a$1.flow("$captain-board").warn("Board task load failed",{error:d instanceof Error?d.message:String(d)});}let i=s.filter(d=>d.external_ref?.provider==="orchestration"&&!d.parentTaskId&&!d.settledAt),a=[];for(let d of i){let _=Fn(s.filter(u=>u.parentTaskId===d.id)),O=[];for(let u of _){let P=t?await $t(u,t):[];O.push({taskId:u.id,blurb:u.blurb,stage:u.stage,status:u.status,claimant:u.claimant,dependsOn:u.dependsOn||[],fragileSymbols:P});}a.push({epicTaskId:d.id,blurb:d.blurb,runStatus:Rn(d,_),settledAt:d.settledAt,nodes:O});}let c=s.filter(d=>d.status==="open"&&!d.claimant),l=[];for(let d of c){let{score:_,fragile:O}=t?await An(d,t):{score:0,fragile:[]},u;e.proposeClaimants&&(u=await Nn(d,n)),l.push({taskId:d.id,blurb:d.blurb,priority:d.priority,tags:d.tags||[],rippleScore:_,fragileSymbols:O,proposedClaimant:u});}l.sort((d,_)=>{if(_.rippleScore!==d.rippleScore)return _.rippleScore-d.rippleScore;let O=(Tt[d.priority]??1)-(Tt[_.priority]??1);return O!==0?O:_.taskId.localeCompare(d.taskId)});let p=s.filter(d=>d.status==="in-progress").length,f=s.filter(d=>d.status==="open").length,k=new Set(i.map(d=>d.id)),w=new Set(c.map(d=>d.id)),x=[];for(let d of s){if(!d.id||d.status==="done"||d.status==="shelved"||d.parentTaskId||k.has(d.id)||w.has(d.id))continue;let _=t?await $t(d,t):[];x.push({taskId:d.id,blurb:d.blurb,stage:d.stage,status:d.status,claimant:d.claimant,dependsOn:d.dependsOn||[],fragileSymbols:_});}let{validateTaskDag:y}=await import('./task-loader-LFEE6OU7.js'),j=y(s),N=a.filter(d=>!d.settledAt&&d.nodes.length>0&&d.nodes.every(_=>_.status==="done"||_.status==="shelved")).map(d=>({epicTaskId:d.epicTaskId,blurb:d.blurb,reason:"all children terminal but run never settled"})),F=7,$=Date.now(),A=s.filter(d=>d.status==="open"&&d.claimant?.kind==="archetype"&&!d.started_at).map(d=>({task:d,ageDays:Math.floor(($-new Date(d.created).getTime())/864e5)})).filter(({ageDays:d})=>Number.isFinite(d)&&d>=F).map(({task:d,ageDays:_})=>({taskId:d.id,blurb:d.blurb,claimant:d.claimant,ageDays:_}));return {runs:a,unclaimed:l,loose:x,summary:{runs:a.length,open:f,inFlight:p,unclaimed:l.length,loose:x.length},integrity:j.length>0?j:void 0,settlementDebt:N.length>0?N:void 0,staleClaims:A.length>0?A:void 0}}async function Nn(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-S2ESNKSA.js'),r=t(e);if(!r?.agents)return;let s=[n.blurb,...n.tags||[]].join(" "),i=o(s,r.agents);return i.length===0?void 0:{kind:"archetype",ref:i[0].name}}catch{return}}async function En(n,e){let o=n.taskId,t=n.claimant;if(!o||!t?.kind||!t?.ref)return {handled:true,text:JSON.stringify({ok:false,error:"claim requires taskId and claimant {kind, ref}"})};let{loadTask:r,updateTask:s}=await import('./task-loader-LFEE6OU7.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=i.claimant;if(a&&a.kind!=="archetype"&&t.kind==="archetype")return a$1.flow("$captain-board").info("Claim rejected: archetype cannot override human/peer claim",{taskId:o,existing:a.kind,proposed:t.kind}),{handled:true,text:JSON.stringify({ok:false,error:`task ${o} is claimed by ${a.kind}:${a.ref}; archetype proposal cannot override`,claimant:a})};let c=await s(e.rootDir,o,{claimant:t});return a$1.flow("$captain-board").info("Captain claim written",{taskId:o,claimant:t,ok:c}),{handled:true,text:JSON.stringify({ok:c,taskId:o,claimant:t,status:"open"})}}async function $n(n,e){let o=n.taskId,t=n.blockedOn;if(!o||!t)return {handled:true,text:JSON.stringify({ok:false,error:"advance requires taskId and blockedOn (v7.0 has no 'blocked' status \u2014 advance records a reason only)"})};let{loadTask:r,updateTask:s}=await import('./task-loader-LFEE6OU7.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=await s(e.rootDir,o,{blocked_on:t});return a$1.flow("$captain-board").info("Captain advance: blocked_on recorded (status unchanged)",{taskId:o,blockedOn:t,status:i.status,ok:a}),{handled:true,text:JSON.stringify({ok:a,taskId:o,blocked_on:t,status:i.status})}}function Tn(n){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),o=n.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],t=n.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(s=>s.toLowerCase()).filter(s=>s.length>2&&!e.has(s));return [...new Set([...o,...t])].slice(0,6)}function Wn(n){let e=[],o=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,t;for(;(t=o.exec(n))!==null;)e.push(t[1]);let r=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(t=r.exec(n))!==null;)e.includes(t[0])||e.push(t[0]);return e}function Wt(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Ln(n){switch(n){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function Hn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Mn(n,e,o){let t=Math.round(n*100);switch(e){case "sparse":return `${t}% of ${o} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${t}% of ${o} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${t}% of ${o} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${t}% of ${o} director(ies) covered. Area is fully mapped.`}}function Bn(n){let e=[],o="\u2501".repeat(52);e.push(`${o}`),e.push("");let t=n.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${t}`);let r=n.symbols.slice(0,5).map(p=>p.id).join(", ")||"(none found)";e.push(`Symbols: ${r}`);let s=n.blastRadius.affectedFiles.length+n.territory.files.length,i=n.blastRadius.affectedFlows.length,a=n.blastRadius.affectedGates.length,c=n.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${n.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${s} files \xB7 ${i} flows \xB7 ${a} gates${c}`),n.gates.length>0){let p=n.gates.slice(0,2).map(f=>`${f.route} \u2192 ${f.gate} (${f.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${p.join("; ")}`);}if(n.protocol.matched){let p=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${p} \u2014 matched`);}else e.push("Protocol: (none matched)");n.warnings.length>0&&e.push(`Warnings: "${n.warnings[0].slice(0,80)}"`);let l=Math.round(n.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${n.coverage.label}`),e.push(""),e.push(`${o}`),e.join(`
11
+ `).filter(s=>s.trim().length>0),r=Date.now()-Pn;for(let s of t.slice(-50))try{let i=JSON.parse(s),a=i.ts?new Date(i.ts).getTime():NaN;if(Number.isNaN(a)||a<r)continue;if(i.stages?.runPostflightLearning==="ok")return !0}catch{}}catch{return false}return false}async function Dn(n,e){let o=n.action||"read";if(o==="claim")return En(n,e);if(o==="advance")return $n(n,e);let t=await On(e.rootDir,{},e),r=JSON.stringify(t,null,2);return O(r.length,"paradigm_captain_board"),{handled:true,text:r}}function Rn(n,e){return n.settledAt?n.crashed_at||e.some(t=>t.crashed_at)?"crashed":"settled":e.length===0?"pending":e.some(t=>t.status==="in-progress")||n.status==="in-progress"?"in-progress":"pending"}function Fn(n){return [...n].sort((e,o)=>{let t=e.stage??0,r=o.stage??0;if(t!==r)return t-r;let s=e.dependsOn?.length??0,i=o.dependsOn?.length??0;return s!==i?s-i:e.id.localeCompare(o.id)})}async function $t(n,e){let o=Lt(n).slice(0,3),t=[];for(let r of o)try{let s=await le("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var In=/[#$^!~][a-z][a-z0-9-]*/gi;function Lt(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(In)||[];for(let t of o)e.add(t);return Array.from(e)}async function An(n,e){let o=Lt(n).slice(0,3),t=0,r=[];for(let s of o)try{let i=await le("paradigm_ripple",{symbol:s,depth:2,response_format:"concise"},e);if(i.handled){let a=JSON.parse(i.text),c=a.analysis?.directlyAffected?.length??0,l=a.analysis?.indirectlyAffected?.length??0;t+=c*2+l,a.impact==="high"&&!r.includes(s)&&r.push(s);}}catch{}return {score:t,fragile:r}}var Tt={high:0,medium:1,low:2};async function On(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-INPLZRG5.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(d){a$1.flow("$captain-board").warn("Board task load failed",{error:d instanceof Error?d.message:String(d)});}let i=s.filter(d=>d.external_ref?.provider==="orchestration"&&!d.parentTaskId&&!d.settledAt),a=[];for(let d of i){let _=Fn(s.filter(u=>u.parentTaskId===d.id)),O=[];for(let u of _){let P=t?await $t(u,t):[];O.push({taskId:u.id,blurb:u.blurb,stage:u.stage,status:u.status,claimant:u.claimant,dependsOn:u.dependsOn||[],fragileSymbols:P});}a.push({epicTaskId:d.id,blurb:d.blurb,runStatus:Rn(d,_),settledAt:d.settledAt,nodes:O});}let c=s.filter(d=>d.status==="open"&&!d.claimant),l=[];for(let d of c){let{score:_,fragile:O}=t?await An(d,t):{score:0,fragile:[]},u;e.proposeClaimants&&(u=await Nn(d,n)),l.push({taskId:d.id,blurb:d.blurb,priority:d.priority,tags:d.tags||[],rippleScore:_,fragileSymbols:O,proposedClaimant:u});}l.sort((d,_)=>{if(_.rippleScore!==d.rippleScore)return _.rippleScore-d.rippleScore;let O=(Tt[d.priority]??1)-(Tt[_.priority]??1);return O!==0?O:_.taskId.localeCompare(d.taskId)});let p=s.filter(d=>d.status==="in-progress").length,f=s.filter(d=>d.status==="open").length,k=new Set(i.map(d=>d.id)),w=new Set(c.map(d=>d.id)),x=[];for(let d of s){if(!d.id||d.status==="done"||d.status==="shelved"||d.parentTaskId||k.has(d.id)||w.has(d.id))continue;let _=t?await $t(d,t):[];x.push({taskId:d.id,blurb:d.blurb,stage:d.stage,status:d.status,claimant:d.claimant,dependsOn:d.dependsOn||[],fragileSymbols:_});}let{validateTaskDag:y}=await import('./task-loader-INPLZRG5.js'),j=y(s),N=a.filter(d=>!d.settledAt&&d.nodes.length>0&&d.nodes.every(_=>_.status==="done"||_.status==="shelved")).map(d=>({epicTaskId:d.epicTaskId,blurb:d.blurb,reason:"all children terminal but run never settled"})),F=7,$=Date.now(),A=s.filter(d=>d.status==="open"&&d.claimant?.kind==="archetype"&&!d.started_at).map(d=>({task:d,ageDays:Math.floor(($-new Date(d.created).getTime())/864e5)})).filter(({ageDays:d})=>Number.isFinite(d)&&d>=F).map(({task:d,ageDays:_})=>({taskId:d.id,blurb:d.blurb,claimant:d.claimant,ageDays:_}));return {runs:a,unclaimed:l,loose:x,summary:{runs:a.length,open:f,inFlight:p,unclaimed:l.length,loose:x.length},integrity:j.length>0?j:void 0,settlementDebt:N.length>0?N:void 0,staleClaims:A.length>0?A:void 0}}async function Nn(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-GFNPCEUU.js'),r=t(e);if(!r?.agents)return;let s=[n.blurb,...n.tags||[]].join(" "),i=o(s,r.agents);return i.length===0?void 0:{kind:"archetype",ref:i[0].name}}catch{return}}async function En(n,e){let o=n.taskId,t=n.claimant;if(!o||!t?.kind||!t?.ref)return {handled:true,text:JSON.stringify({ok:false,error:"claim requires taskId and claimant {kind, ref}"})};let{loadTask:r,updateTask:s}=await import('./task-loader-INPLZRG5.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=i.claimant;if(a&&a.kind!=="archetype"&&t.kind==="archetype")return a$1.flow("$captain-board").info("Claim rejected: archetype cannot override human/peer claim",{taskId:o,existing:a.kind,proposed:t.kind}),{handled:true,text:JSON.stringify({ok:false,error:`task ${o} is claimed by ${a.kind}:${a.ref}; archetype proposal cannot override`,claimant:a})};let c=await s(e.rootDir,o,{claimant:t});return a$1.flow("$captain-board").info("Captain claim written",{taskId:o,claimant:t,ok:c}),{handled:true,text:JSON.stringify({ok:c,taskId:o,claimant:t,status:"open"})}}async function $n(n,e){let o=n.taskId,t=n.blockedOn;if(!o||!t)return {handled:true,text:JSON.stringify({ok:false,error:"advance requires taskId and blockedOn (v7.0 has no 'blocked' status \u2014 advance records a reason only)"})};let{loadTask:r,updateTask:s}=await import('./task-loader-INPLZRG5.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a=await s(e.rootDir,o,{blocked_on:t});return a$1.flow("$captain-board").info("Captain advance: blocked_on recorded (status unchanged)",{taskId:o,blockedOn:t,status:i.status,ok:a}),{handled:true,text:JSON.stringify({ok:a,taskId:o,blocked_on:t,status:i.status})}}function Tn(n){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),o=n.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],t=n.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(s=>s.toLowerCase()).filter(s=>s.length>2&&!e.has(s));return [...new Set([...o,...t])].slice(0,6)}function Wn(n){let e=[],o=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,t;for(;(t=o.exec(n))!==null;)e.push(t[1]);let r=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(t=r.exec(n))!==null;)e.includes(t[0])||e.push(t[0]);return e}function Wt(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Ln(n){switch(n){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function Hn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Mn(n,e,o){let t=Math.round(n*100);switch(e){case "sparse":return `${t}% of ${o} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${t}% of ${o} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${t}% of ${o} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${t}% of ${o} director(ies) covered. Area is fully mapped.`}}function Bn(n){let e=[],o="\u2501".repeat(52);e.push(`${o}`),e.push("");let t=n.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${t}`);let r=n.symbols.slice(0,5).map(p=>p.id).join(", ")||"(none found)";e.push(`Symbols: ${r}`);let s=n.blastRadius.affectedFiles.length+n.territory.files.length,i=n.blastRadius.affectedFlows.length,a=n.blastRadius.affectedGates.length,c=n.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${n.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${s} files \xB7 ${i} flows \xB7 ${a} gates${c}`),n.gates.length>0){let p=n.gates.slice(0,2).map(f=>`${f.route} \u2192 ${f.gate} (${f.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${p.join("; ")}`);}if(n.protocol.matched){let p=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${p} \u2014 matched`);}else e.push("Protocol: (none matched)");n.warnings.length>0&&e.push(`Warnings: "${n.warnings[0].slice(0,80)}"`);let l=Math.round(n.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${n.coverage.label}`),e.push(""),e.push(`${o}`),e.join(`
12
12
  `)}function Jn(n,e,o){let r=o.filter(s=>E.dirname(s)===e).slice(0,3).map(s=>`# - ${E.basename(s)}`).join(`
13
13
  `);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
14
14
  # Delegate to Scribe (Documentor) for rich documentation